Page 1 of 3 123 LastLast
Results 1 to 40 of 98

Thread: Sql Count

  1. #1

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Sql Count

    Hello everybody! My code below will INSERT records in my two tables namely "tblStockMasterFile and tblStockFile". When the Save button is clicked it checks whether a product ID entered already exists or not. If product exists then the records will be save in tblStocktransFile Only otherwise to both tables. I attached the table for reference.

    Code:
    Private Sub cmdSave_Click()
      If CheckNullValue = False Then Exit Sub
      Call ReplaceQuotation(txtProdName)
    
    On Error GoTo ErrHandler
      If Checker = True Then  'Product ID already Exist then save in tblStocktransFile Only
        
        sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice, Quantity, Reason,Sequence)" & _
                  "VALUES('" & txtProdID.Text & "','" & txtEntryDate.Text & "','" & txtProdPurchasePrice.Text & _
                       "','" & txtProdQTY.Text & " ','" & txtReason.Text & "','" & txtSEQ.Text & "')"
                     '  Debug.Print sSQL
        oConn.Execute sSQL
      
      Else  'Product ID does not Exist so save in both tblStockMasterFile and tblStockTransFile
        
        oConn.BeginTrans
          
            sSQL = "INSERT INTO tblStockMasterFile(ProductID, ProductName,Unit,ReOrderPoint)" & _
                  "VALUES( '" & txtProdID.Text & "','" & txtProdName.Text & "','" & txtProdUnit.Text & " ', '" & txtProdReOrderPoint.Text & "')"
          oConn.Execute sSQL
      
            sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice, Quantity, Reason,Sequence)" & _
                  "VALUES('" & txtProdID.Text & "','" & txtEntryDate.Text & "','" & txtProdPurchasePrice.Text & _
                       "','" & txtProdQTY.Text & " ','" & txtReason.Text & "','" & txtSEQ.Text & "')"
                     '  Debug.Print sSQL
          oConn.Execute sSQL
    
        oConn.CommitTrans
        
      End If
      
      Call FillListView(lstStockMasterFile, rsStock)
      Call ClearFunction(frmStockMasterFile, "TextBox")
    
      txtProdID.SetFocus
      Exit Sub
    
    ErrHandler:
      Call msgError(Err)
    End Sub 'cmdSave_Click
    I would like instead of checking the ProductID only, I would also like to check the entry date and if the date already exists for the same product ID i would like to the program to increment the existing sequence value i have in my tblStockTransFile so that there's no need for the user to remember the last sequence value for each of the products and manually type it.
    Code:
    For example:
    productID: 01
    ProductName: Colgate
    Unit: Tube
    PurchasePrice: 30.00
    Quantity:100
    Reason: In --->StockIn
    EntryDate: 9/15/07
    ReOrderPoint: 10
    Sequence: 1
    If I add more stock to the product the program should look into the sequence value and add 1 to it.

    Below is function checker. It lacks the entrycode and I dont know how or what should i add to it. Can someone please help me out please?
    Code:
    'TODO : return true if ProductID already exist
    Private Function Checker() As Boolean
      Checker = False
    
      If rsTempStock.State = adStateOpen Then rsTempStock.Close
      sSQL1 = "SELECT COUNT(ProductID) as ProductIDExist " & _
             "FROM tblStockMasterFile " & _
             "WHERE ProductID = '" & (txtProdID.Text) & "'"
      'Debug.Print sSQL1
      rsTempStock.Open sSQL1, oConn, adOpenKeyset, adLockReadOnly
    
      If rsTempStock("ProductIDExist") > 0 Then Checker = True
    End Function  'Function Checker
    I am thinking of adding another check function for the date like the code below but I guess it's not how it is done.
    Code:
    'TODO : return true if Date already exist
    Private Function DateChecker() As Boolean
      DateChecker = False
    
      If rsTempStock.State = adStateOpen Then rsTempStock.Close
      sSQL1 = "SELECT COUNT(EntryDate) as DateExist " & _
             "FROM tblStockTransFile " & _
             "WHERE EntryDate = '" & (txtEntryDate.Text) & "'"
      'Debug.Print sSQL1
      rsTempStock.Open sSQL1, oConn, adOpenKeyset, adLockReadOnly
    
      If rsTempStock("DateExist") > 0 Then Checker = True
    End Function  'Function DateChecker
    Attached Images Attached Images  
    Last edited by Simply Me; Sep 15th, 2007 at 05:16 AM.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  2. #2

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I've edited my first to make it more understandable.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  3. #3
    VB Guru ganeshmoorthy's Avatar
    Join Date
    Dec 2005
    Location
    Sharjah, United Arab Emirates
    Posts
    3,031

    Re: Sql Count

    I dint go thru it fully...but found something you missed in the DateChecker...
    Quote Originally Posted by Simply Me
    vb Code:
    1. Private Function DateChecker() As Boolean
    2.   DateChecker = False
    3.  
    4.   If rsTempStock.State = adStateOpen Then rsTempStock.Close
    5.   sSQL1 = "SELECT COUNT(EntryDate) as DateExist " & _
    6.          "FROM tblStockTransFile " & _
    7.          "WHERE EntryDate = '" & (txtEntryDate.Text) & "'"
    8.   'Debug.Print sSQL1
    9.   rsTempStock.Open sSQL1, oConn, adOpenKeyset, adLockReadOnly
    10.  
    11.   If rsTempStock("DateExist") > 0 Then Checker = True ' <---this should be DateChecker
    12. End Function  'Function DateChecker
    If an answer to your question has been helpful, then please, Rate it!

    Have done Projects in Access and Member management systems using BioMetric devices, Smart cards and BarCodes.


  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    This would be the query to return the next sequence number for a product on a given entry date - all in one query - all in one step.

    Code:
    Select IsNull(Max(Sequence),0)+1
          From tblStockTransFile
          Where ProductId='xyz' and EntryDate='09/01/2007'
    The IsNull() is a MS SQL function - NZ() I believe would be the ACCESS equivalent.

    Keep in mind that even though this returns the proper sequence number to use - in a multi-user system that won't really work.

    If you are using MS SQL SERVER (I think you are using EXPRESS?) then you should really investigate STORED PROCEDURES. Using these will really make the multi-user aspect of a system much easier to conquer.

    Here is the proof of concept

    Code:
    Create Table #Test (ProdId varchar(3), EntryDate datetime, SeqNo int)
    
    Insert into #Test values ('XYZ','2007-09-15',1)
    Insert into #Test values ('XYZ','2007-09-15',2)
    
    Select IsNull(Max(SeqNo),0)+1
          From #Test
          Where ProdId='xyz' and EntryDate='09/01/2007'
    
    Select IsNull(Max(SeqNo),0)+1
          From #Test
          Where ProdId='xyz' and EntryDate='09/15/2007'
    
    Drop Table #Test
    and this returns

    Code:
                 
    ----------- 
    1
    
                
    ----------- 
    3
    Last edited by szlamany; Sep 15th, 2007 at 11:54 AM.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  5. #5

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Quote Originally Posted by ganeshmoorthy
    I dint go thru it fully...but found something you missed in the DateChecker...
    Thanks for pointing that out.

    Quote Originally Posted by szlamany
    This would be the query to return the next sequence number for a product on a given entry date - all in one query - all in one step.

    Code:
    Select IsNull(Max(Sequence),0)+1
          From tblStockTransFile
          Where ProductId='xyz' and EntryDate='09/01/2007'
    The IsNull() is a MS SQL function - NZ() I believe would be the ACCESS equivalent.
    Where does this code fit in to my code above?
    Quote Originally Posted by szlamany
    Keep in mind that even though this returns the proper sequence number to use - in a multi-user system that won't really work.

    If you are using MS SQL SERVER (I think you are using EXPRESS?) then you should really investigate STORED PROCEDURES. Using these will really make the multi-user aspect of a system much easier to conquer.
    As what we have discussed in other thread, I am learning EXPRESS but then i have to finish this one before the month end and Im having trouble with attach option in EXPRESS, so, i guess i have to use MS ACCESS for now and then later have to convert it using EXPRESS.

    It is not for multi-user for now but it would be good to prepare it for multi-user.

    Is my code logic above correct? need your confirmation.
    Back to the SEQ topic....Am correct in my analysis that on every DATE that there is an entry the SEQ value will always be "1"? If so, then for the whole year round the table would grow up.
    Last edited by Simply Me; Sep 16th, 2007 at 02:39 AM.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  6. #6

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Is this meant to replace my checker function or i just add it be my checker or another function to be called?
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  7. #7

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Im sorry for the question in post #'s 5 & 6, I just realized that I have to put that in my cmdSave button. Right now, i have this error when I tried it. "Wrong number of arguments used with function in query expression 'IsNull(Max(Sequence),0)+1'"

    vb Code:
    1. Private Sub cmdSave_Click()
    2.   If CheckNullValue = False Then Exit Sub
    3.   Call ReplaceQuotation(txtProdName)
    4.  
    5. On Error GoTo ErrHandler
    6.   If Checker = True Then  'Product ID already Exist then save in tblStocktransFile Only
    7.     oConn.BeginTrans
    8.    
    9.       sSQL = "SELECT IsNull(Max(Sequence),0)+1 " & _
    10.               "FROM tblStockTransFile " & _
    11.                   "WHERE ProductID='" & txtProdID.Text & "' AND EntryDate=" & DTEntryDate.Value & ""
    12.       oConn.Execute sSQL
    13.      
    14.       sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice,Quantity, Reason,Sequence)" & _
    15.               "VALUES('" & txtProdID.Text & "'," & Format$(DTEntryDate.Value, "mm-dd-yyyy") & _
    16.                    ",'" & txtProdPurchasePrice.Text & "','" & txtProdQTY.Text & " ','In ','" & txtSEQ.Text & "')"
    17.                   'Debug.Print sSQL
    18.                   '" & rsStock.Fields("Sequence") + 1 & "'
    19.       oConn.Execute sSQL
    20.      
    21.     oConn.CommitTrans
    22.   Else  'Product ID does not Exist so save in both tblStockMasterFile and tblStockTransFile
    23.    
    24.     oConn.BeginTrans
    25.      
    26.         sSQL = "INSERT INTO tblStockMasterFile(ProductID, ProductName,Unit,ReOrderPoint)" & _
    27.               "VALUES( '" & txtProdID.Text & "','" & txtProdName.Text & "','" & txtProdUnit.Text & " ', '" & txtProdReOrderPoint.Text & "')"
    28.       oConn.Execute sSQL
    29.  
    30.         sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice, Quantity, Reason,Sequence)" & _
    31.               "VALUES('" & txtProdID.Text & "','" & DTEntryDate.Value & "','" & txtProdPurchasePrice.Text & _
    32.                    "','" & txtProdQTY.Text & " ','In ','" & txtSEQ.Text & "')"
    33.                  '  Debug.Print sSQL
    34.       oConn.Execute sSQL
    35.  
    36.     oConn.CommitTrans
    37.    
    38.   End If
    39.  
    40.   Call FillListView(lstStockMasterFile, rsStock)
    41.   Call ClearFunction(frmStockMasterFile, "TextBox")
    42.  
    43.   txtProdID.SetFocus
    44.   Exit Sub
    45.  
    46. ErrHandler:
    47.   Call msgError(Err)
    48. End Sub 'cmdSave_Click
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  8. #8

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I changed the IsNull to NZ since i am using MS ACCESS and i get this error "Undefined function 'NZ' in expression."
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  9. #9
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    I don't use ACCESS so I don't know the replacement syntax for the functon ISNULL which is missing from ACCESS. I thought it was NZ() - you would have to look that up yourself.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  10. #10
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    btw - I see in your code that you have a BEGINTRAN and some SQL statements. If they get an error you do a MSGBOX.

    Do you realize that the transaction is held open while the user if thinking about clicking OK to that MSGBOX? You need to ROLLBACK or COMMIT a transaction immediately!

    This is really, really bad.

    You should get over your SQL EXPRESS issue and you should have started using STORED PROCEDURES in SQL EXPRESS. This would have made your entire SQL life 100% easier. All SQL would be done in STORED PROCEDURES written into the database.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  11. #11

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Quote Originally Posted by szlamany
    btw - I see in your code that you have a BEGINTRAN and some SQL statements. If they get an error you do a MSGBOX.

    Do you realize that the transaction is held open while the user if thinking about clicking OK to that MSGBOX? You need to ROLLBACK or COMMIT a transaction immediately!

    This is really, really bad.

    You should get over your SQL EXPRESS issue and you should have started using STORED PROCEDURES in SQL EXPRESS. This would have made your entire SQL life 100% easier. All SQL would be done in STORED PROCEDURES written into the database.
    I already have a msgbox in my errorhandler i am just missing this " oConn.RollbackTrans"

    I really really to migrate to SQL EXPRESS now but I am afraid i might not finish this if i have to learn Stored Procedures and not to mention my issue about the attach option.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  12. #12

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    ok I am using I changed my connection already I'm using SQL EXPRESS. I added the RollbackTrans already.

    I tried your code with the IsNull and the attached pic shows my error.

    One of my problem using SQL EXPRESS is this, the project which im working with is in my flash drive so if i want to work on it anytime i can not just do it becuase the database is not present since i cannot copy the database.
    Attached Images Attached Images  
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  13. #13
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    The point about using SPROCS is that you put the INSERT statements into a PROCEDURE.

    You develop and test them in a query window.

    Not in the VB code.

    The VB code simply calls the SPROC by passing the important parameters to it. The VB code never ever needs to use BEGIN TRAN or COMMIT or ROLLBACK - that's all does in the isolation of the SPROC.

    This separates the UI from the business logic and makes you more productive.

    The ATTACHDBFILENAME is easy to use.

    So - how do we proceed from here?

    Do we get your ATTACHDBFILENAME issue fixed? From another thread of yours...

    Quote Originally Posted by Simply Me
    yes i've seen it and where will add the highlighted part of code in the code you post in #17?
    Code:
    'Source=.\SQLEXPRESS;AttachDbFilename="C:\BigLongPathName\MyDataFile1.mdf";Integrated Security=True;Connect Timeout=30;User Instance=True
    the pathname of the db file, if this is possible then i just can copy the .mdf file and put it in the same folder with my vb files...so that i will not install anymore sql express to the local machine where i will install the prog.
    Do we learn about calling SPROCS from VB?

    Do we learn about writing SPROCS??

    Let's get at least one of these 100% understood and conquered.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  14. #14

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Quote Originally Posted by szlamany
    So - how do we proceed from here?

    Do we get your ATTACHDBFILENAME issue fixed? From another thread of yours...



    Do we learn about calling SPROCS from VB?

    Do we learn about writing SPROCS??

    Let's get at least one of these 100% understood and conquered.
    I say YES to all your questions. I like to learn those as we go through this project in fact as we are discussing im reading a about SPROCS.

    First, the issue on the sequence field. I attached the error i recieved using it.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  15. #15
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    If we are doing STORED PROCEDURES first - then show me the code for the SPROC that you have.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  16. #16

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I dont have any yet as I am only starting reading it.

    The code I have right now is this which is part working. Part working I say because the first time i enter a product it accept it assigned a sequence "0" and is save in the tables but the second time i enter the same product it again accepts it but then the sequence is still "0" and what puzzles me is the Date that it save is not correct instead of "9/16/2007" is saves "6/27/1894" and the third time i enter the same product it already gave me an error message "violation of PRIMARY KEY ConstraintPK_tblStockTransFile. Cannot insert duplicate key in object dbo.tblStockTransFile
    vb Code:
    1. Private Sub cmdSave_Click()
    2.   If CheckNullValue = False Then Exit Sub
    3.   Call ReplaceQuotation(txtProdName)
    4. On Error GoTo ErrHandler
    5.   If Checker = True Then  'Product ID already Exist then save in tblStocktransFile Only
    6.     oConn.BeginTrans
    7.  
    8.       sSQL = "SELECT IsNull(Max(Sequence),0)+1 " & _
    9.               "FROM tblStockTransFile " & _
    10.                   "WHERE ProductID='" & txtProdID.Text & "' AND EntryDate=" & DTEntryDate.Value & ""
    11.                   Debug.Print sSQL
    12.       oConn.Execute sSQL
    13.      
    14.       sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice,Quantity, Reason)" & _
    15.               "VALUES('" & txtProdID.Text & "'," & Format$(DTEntryDate.Value, "mm-dd-yyyy") & _
    16.                    ",'" & txtProdPurchasePrice.Text & "','" & txtProdQTY.Text & "','In')"
    17.                   Debug.Print sSQL
    18.                   '" & rsStock.Fields("Sequence") + 1 & "'
    19.       oConn.Execute sSQL
    20.      
    21.     oConn.CommitTrans
    22.   Else  'Product ID does not Exist so save in both tblStockMasterFile and tblStockTransFile
    23.    
    24.     oConn.BeginTrans
    25.      
    26.       sSQL = "INSERT INTO tblStockMasterFile(ProductID, ProductName,Unit,ReOrderPoint)" & _
    27.                 "VALUES( '" & txtProdID.Text & "','" & txtProdName.Text & "','" & txtProdUnit.Text & " ', '" & txtProdReOrderPoint.Text & "')"
    28.       oConn.Execute sSQL
    29.      
    30.       sSQL = "SELECT IsNull(Max(Sequence),0 )+ 1" & _
    31.               "FROM tblStockTransFile " & _
    32.                   "WHERE ProductID='" & txtProdID.Text & "' AND EntryDate=" & DTEntryDate.Value & ""
    33.                   Debug.Print sSQL
    34.       oConn.Execute sSQL
    35.      
    36.       sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice, Quantity, Reason)" & _
    37.                 "VALUES('" & txtProdID.Text & "','" & DTEntryDate.Value & "','" & txtProdPurchasePrice.Text & _
    38.                    "','" & txtProdQTY.Text & " ','In')"
    39.                  '  Debug.Print sSQL
    40.       oConn.Execute sSQL
    41.  
    42.    
    43.     oConn.CommitTrans
    44.    
    45.   End If
    46.  
    47.   Call FillListView(lstStockMasterFile, rsStock)
    48.   Call ClearFunction(frmStockMasterFile, "TextBox")
    49.  
    50.   txtProdID.SetFocus
    51.   Exit Sub
    52.  
    53. ErrHandler:
    54.   oConn.RollbackTrans
    55.   Call msgError(Err)
    56. End Sub 'cmdSave_Click
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  17. #17
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    We don't like IN-LINE SQL in our shop - it's a pain to build and debug. You have date issues - as 100's of other people have had on the forum. You are not formatting your dates consistently in all your SQL statements...

    Using SPROCS makes all this easier.

    Unfortunately I do not have time to look at your VB code to get it cleaned up.

    I've got a deliverable I'm working on for Monday AM on a pocket PC that's giving me my own headaches.

    I suggested 3 things I could do with you today - if you are interested in conquering any of those 3 I'm available.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  18. #18

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Quote Originally Posted by szlamany
    We don't like IN-LINE SQL in our shop - it's a pain to build and debug. You have date issues - as 100's of other people have had on the forum. You are not formatting your dates consistently in all your SQL statements...

    Using SPROCS makes all this easier.

    Unfortunately I do not have time to look at your VB code to get it cleaned up.

    I've got a deliverable I'm working on for Monday AM on a pocket PC that's giving me my own headaches.

    I suggested 3 things I could do with you today - if you are interested in conquering any of those 3 I'm available.
    I am very much interested to learn.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  19. #19
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    Creating a procedure is done in a query window - in Management Studio.

    The procedure is saved as a .SQL text file from that window.

    Here's an example of a small procedure we have.

    Code:
    USE TCS
    GO
    SET QUOTED_IDENTIFIER ON 
    GO
    SET ANSI_NULLS ON 
    GO
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[frmPerTax_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[frmPerTax_Update]
    GO
    
    Create Procedure frmPerTax_Update
    	 @Towncode varchar(2)
    	,@Yr int
    	,@BillNum varchar(10)
    	,@Closed varchar(1)
    	,@Comment varchar(50)
    as
    
    Set NoCount On
    
    Update PerTax_T Set Closed=IsNull(@Closed,'')
    		,Comment=IsNull(@Comment,'')
    		Where Yr=@Yr and Town=@Towncode and BillNum=@BillNum
    
    GO
    GRANT EXECUTE ON frmPerTax_Update TO TCSUser
    Go
    SET QUOTED_IDENTIFIER OFF 
    GO
    SET ANSI_NULLS ON 
    GO
    This creates the SPROC - does it make sense? Please review it and ask questions on any item you are unclear on.

    You have parameters that are passed from VB into the SPROC - and they are properly datatyped. And those parameter variables are used in the SQL statements throughout the SPROC.

    Your SPROC for UPDATE would need to have parameters for each value you need - with the proper datatype. Your SAVE sproc would have each of your INSERTS in that one sproc - so it's doing all the work in one single call.

    You test the SPROC from another QUERY WINDOW - with something like this:

    Code:
    Begin Tran
    Exec frmPerTax_Update '01',2007,'0000123','Y','WE JUST CLOSED THIS BILL'
    Select * From PerTax_T Where BillNum='0000123'
    Rollback
    Notice how the testing is wrapped in a BEGIN TRAN/ROLLBACK - that is done so we can test dozens of calls without messing with our tables for real. The SELECT after the EXEC is an example of me wanting to see the results of my SPROC execution - testing that is actually worked.

    So all this SPROC work is done outside of VB - and it's extremely easy to produce working SQL procedures with this.

    Don't even think about calling them from VB first - you develop and test them all in Management Studio.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  20. #20

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Quote Originally Posted by szlamany
    Creating a procedure is done in a query window - in Management Studio.

    The procedure is saved as a .SQL text file from that window.

    Here's an example of a small procedure we have.

    [code]USE TCS
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    SET ANSI_NULLS ON
    GO
    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[frmPerTax_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[frmPerTax_Update]
    GO
    This is checking if the procedure exists if it exists then drop it right? Questiono I need to use * all the time?
    Create Procedure frmPerTax_Update
    @Towncode varchar(2)
    ,@Yr int
    ,@BillNum varchar(10)
    ,@Closed varchar(1)
    ,@Comment varchar(50)
    as

    Set NoCount On

    Update PerTax_T Set Closed=IsNull(@Closed,'')
    ,Comment=IsNull(@Comment,'')
    Where Yr=@Yr and Town=@Towncode and BillNum=@BillNum

    GO
    GRANT EXECUTE ON frmPerTax_Update TO TCSUser
    Go
    SET QUOTED_IDENTIFIER OFF
    GO
    SET ANSI_NULLS ON
    GO
    here you created the procedure named as frmPerTax_Update. From the set NoCount ON downwards i down know what are there uses.
    QUOTE]
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  21. #21
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    Exists() is a nice SQL construct. If checks for the existence of rows matching the WHERE clause. It does not actually return anything.

    So the SELECT * is standard and acceptable in an EXISTS() function.

    All those SET statements are simply boilerplate that I've copied from MS examples.

    The GRANT is something you probably would not need - as we have permission issues that we have to deal with in our apps. You could remove the GRANT statement if you need to.

    Now - let's get your SPROC written to insert into the MASTER and TRANS file.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  22. #22

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I have tried creating SPROCS and sucessfully run it.
    vb Code:
    1. Use MasterFile
    2. If EXISTS(SELECT name FROM sysobjects
    3.         WHERE name='myProcedure')
    4.     DROP PROCEDURE myProcedure
    5. GO
    6.  
    7. CREATE PROCEDURE myProcedure
    8. AS
    9. SELECT tblStockMasterFile.ProductID, tblStockMasterFile.ProductName,
    10.           tblStockMasterFile.Unit, tblStockMasterFile.ReOrderPoint,
    11.           tblStockTransFile.EntryDate, tblStockTransFile.Sequence,
    12.           tblStockTransFile.PurchasePrice, tblStockTransFile.Quantity,
    13.           tblStockTransFile.Reason
    14.               FROM tblStockMasterFile INNER JOIN tblStockTransFile ON
    15.                   tblStockMasterFile.ProductID = tblStockTransFile.ProductID
    Can I just call this in my form_load
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  23. #23
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    Put a GO statement after the USE MASTERFILE.

    Each GO statement sends the "prior" command or block of commands to the server to be executed.

    Using this SPROC to get data from your database is great.

    Please show me the VB code you are using to get this executed - we need to make sure you follow proper techniques now before we get burned.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  24. #24

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Im guessing right now as i am reading a book while we talked. I call my this first
    vb Code:
    1. Public Sub openConnection()
    2.   Set oConn = New ADODB.Connection
    3.  
    4.   With oConn
    5.     .Provider = "SQLOLEDB"
    6.     .CursorLocation = adUseClient
    7.     .Properties("Data Source").Value = ".\SQLEXPRESS"
    8.     .Properties("Initial Catalog").Value = "MasterFile"
    9.     .Properties("Integrated Security").Value = "SSPI"
    10.     .CursorLocation = adUseClient
    11. '    .Mode = adModeReadWrite
    12.     .Open
    13.   End With
    14. End Sub
    then i got to have something like this cmd.Commandtype=adCMDStoredProc
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  25. #25

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    here is my old code on form load. I dont what to do next.
    vb Code:
    1. Option Explicit
    2. Dim rsStock As ADODB.Recordset
    3. Dim rsTempStock As ADODB.Recordset
    4. Dim CMD As New ADODB.Command---->i just added this
    5. Dim sSQL$, sSQL1$, iTempProdID$
    6. Dim edwin%
    7.  
    8.  
    9. Private Sub Form_Load()
    10.   Call openConnection
    11.   Me.Left = LeftPos - 400
    12.   Me.Top = TopPos - 200
    13.  
    14.   Set rsStock = New ADODB.Recordset
    15.   Set rsTempStock = New ADODB.Recordset
    16.   rsStock.CursorLocation = adUseClient
    17.  
    18.     sSQL = "SELECT tblStockMasterFile.ProductID, tblStockMasterFile.ProductName, " & _
    19.           "tblStockMasterFile.Unit, tblStockMasterFile.ReOrderPoint, " & _
    20.           "tblStockTransFile.EntryDate, tblStockTransFile.Sequence, " & _
    21.           "tblStockTransFile.PurchasePrice, tblStockTransFile.Quantity, " & _
    22.           "tblStockTransFile.Reason " & _
    23.               "FROM tblStockMasterFile INNER JOIN tblStockTransFile ON " & _
    24.                   "tblStockMasterFile.ProductID = tblStockTransFile.ProductID"
    25.  
    26.   If rsStock.State = adStateOpen Then rsStock.Close
    27.   rsStock.Open sSQL, oConn, adOpenStatic, adLockOptimistic
    28.  
    29.   DTEntryDate.Value = Format(Now,"mm/dd/yyyy") 'Display the Current Date
    30.   Call FillListView(lstStockMasterFile, rsStock)
    31. End Sub 'Form_Load
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  26. #26
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    This creates a command object and a recordset object and executes a stored procedure.

    Code:
    Dim rs As ADODB.Recordset
    
    Set rs = New ADODB.Recordset
    
    Dim offCmnd As ADODB.Command
    
    Set offCmnd = New ADODB.Command
    
    With offCmnd
        .CommandText = "rptDailyAttTeacher"
        .ActiveConnection = gCn
        .CommandType = adCmdStoredProc
        
        .Parameters.Append .CreateParameter("@Yr", adInteger, adParamInput, , frmTeaAttend.lblYr.Caption)
        .Parameters.Append .CreateParameter("@Bldg", adInteger, adParamInput, , frmTeaAttend.gstrBldg)
        .Parameters.Append .CreateParameter("@Attendance_Date", adDate, adParamInput, , Format$(dtpOffice.Value, "SHORT DATE"))
        .Parameters.Append .CreateParameter("@Sort_by_Grade$N_Y", adVarChar, adParamInput, 1, "N")
        .Parameters.Append .CreateParameter("@Final_Report$N_Y", adVarChar, adParamInput, 1, "N")
        Set rs = .Execute()
    End With
    
    Set offCmnd = Nothing
    This one is from a very old program we have - but it has adDate datatypes - which should help you later.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  27. #27

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    this is what i have now before i read your post above
    vb Code:
    1. Private Sub Form_Load()
    2.   Call openConnection
    3.   Me.Left = LeftPos - 400
    4.   Me.Top = TopPos - 200
    5.  
    6.   'Calling myProcedure SPROC
    7.   CMD.ActiveConnection = oConn
    8.   CMD.CommandText = "[myProcedure]"
    9.   CMD.CommandType = adCmdStoredProc
    10.   Set rsStock = CMD.Execute
    11.   Set rsTempStock = CMD.Execute
    12.  
    13.   'DTEntryDate.Value = Date 'Display the Current Date
    14.   Call FillListView(lstStockMasterFile, rsStock)
    15. End Sub 'Form_Load
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  28. #28
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    I don't see you creating or destroying your CMD or RSSTOCK objects - it's nicer to create and destroy them as I hav done.

    Also - you have CMD.Execute on two lines of code - why are you filling two recordsets that way?

    Recordsets are typically used to load data and immediately put it into controls, for instance - not to be retained.

    Are you retaining these recordsets.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  29. #29

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    this is what i have now before i read your post above
    vb Code:
    1. Private Sub Form_Load()
    2.   Call openConnection
    3.   Me.Left = LeftPos - 400
    4.   Me.Top = TopPos - 200
    5.  
    6.   'Calling myProcedure SPROC
    7.   CMD.ActiveConnection = oConn
    8.   CMD.CommandText = "[myProcedure]"
    9.   CMD.CommandType = adCmdStoredProc
    10.   Set rsStock = CMD.Execute
    11.   Set rsTempStock = CMD.Execute
    12.  
    13.   'DTEntryDate.Value = Date 'Display the Current Date
    14.   Call FillListView(lstStockMasterFile, rsStock)
    15. End Sub 'Form_Load
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  30. #30

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    the code now looks like this
    vb Code:
    1. Set rsStock = New ADODB.Recordset
    2.   Set rsTempStock = New ADODB.Recordset
    3.   Set CMD = New ADODB.Command
    4.  
    5.   'Calling myProcedure SPROC
    6.   With CMD
    7.     .ActiveConnection = oConn
    8.     .CommandText = "[myProcedure]"
    9.     .CommandType = adCmdStoredProc
    10.     Set rsStock = .Execute()
    11.     Set rsTempStock = .Execute()
    12.   End With
    but i dont understand the parameters
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  31. #31

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I am destroying them on form_Unload.

    Regarding the rsTempStcok, I use it here
    vb Code:
    1. 'TODO : return true if ProductID already exist
    2. Private Function Checker() As Boolean
    3.   Checker = False
    4.  
    5.   If rsTempStock.State = adStateOpen Then rsTempStock.Close
    6.   sSQL1 = "SELECT COUNT(ProductID) as ProductIDExist " & _
    7.          "FROM tblStockMasterFile " & _
    8.          "WHERE ProductID = '" & (txtProdID.Text) & "'"
    9.   'Debug.Print sSQL1
    10.   rsTempStock.Open sSQL1, oConn, adOpenKeyset, adLockReadOnly
    11.  
    12.   If rsTempStock("ProductIDExist") > 0 Then Checker = True
    13. End Function  'Function Checker
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  32. #32

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    when i added this line
    Code:
        .Parameters.Append .CreateParameter("@EntryDate", adDate, adParamInput, , Format$(DTEntryDate.Value, "SHORT DATE"))
    i got error "Procedure myProcedure has no parameters and arguments were supplied."

    Its late here now, almost 1:00 A.M.
    I guess we have to continue tomorrow night again. It's night time here and I think its day time there.

    thanks for the usual help.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  33. #33
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    The parameters don't come into play on this SPROC - as it's returning all rows - there is no WHERE clause.

    Do you want a WHERE clause?

    You will use a WHERE clause on a UPDATE type of SPROC

    And again - why do you need to exact same copies of the same recordset?

    The code you showed is closing rsTempStock if it's open - so why did you fill it initially????

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  34. #34

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    So there's no need to add the .parameters for now.

    How about the codes in save button. If I make SPROC for it, how do i call it?
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  35. #35
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    Quote Originally Posted by Simply Me
    So there's no need to add the .parameters for now.

    How about the codes in save button. If I make SPROC for it, how do i call it?
    I already said that the UPDATE sproc will have parameters. It was the "select" sproc that had no WHERE clause - right?

    This question makes me think that you are trying to overcome calling the UPDATE sproc and developing the UPDATE sproc all in one moment. That won't work - you need to go through this in stages.

    Develop the SAVE sproc.

    It will have parameters for each field that is being saved and each item in the WHERE clause that fingers the right record.

    You are not supposed to be thinking about calling if from VB - you need to focus on the database requirements first. What fields are being updated - each one needs to be a parameter.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  36. #36

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    I am trying to create procedure for the code below under my SAVE button.
    vb Code:
    1. If Checker = True Then  'Product ID already Exist then save in tblStocktransFile Only
    2.     oConn.BeginTrans
    3.  
    4.       sSQL = "SELECT IsNull(Max(Sequence),0)+1 " & _
    5.               "FROM tblStockTransFile " & _
    6.                   "WHERE ProductID='" & txtProdID.Text & "' AND EntryDate=" & DTEntryDate.Value & ""
    7.                   Debug.Print sSQL
    8.       oConn.Execute sSQL
    9.      
    10.       sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice,Quantity, Reason)" & _
    11.               "VALUES('" & txtProdID.Text & "'," & DTEntryDate.Value & _
    12.                    ",'" & txtProdPurchasePrice.Text & "','" & txtProdQTY.Text & "','In')"
    13.                   Debug.Print sSQL
    14.                   '" & rsStock.Fields("Sequence") + 1 & "'
    15.       oConn.Execute sSQL
    16.      
    17.     oConn.CommitTrans
    18.   Else  'Product ID does not Exist so save in both tblStockMasterFile and tblStockTransFile
    19.    
    20.     oConn.BeginTrans
    21.      
    22.       sSQL = "INSERT INTO tblStockMasterFile(ProductID, ProductName,Unit,ReOrderPoint)" & _
    23.                 "VALUES( '" & txtProdID.Text & "','" & txtProdName.Text & "','" & txtProdUnit.Text & " ', '" & txtProdReOrderPoint.Text & "')"
    24.       oConn.Execute sSQL
    25.      
    26.       sSQL = "SELECT IsNull(Max(Sequence),0 )+ 1" & _
    27.               "FROM tblStockTransFile " & _
    28.                   "WHERE ProductID='" & txtProdID.Text & "' AND EntryDate=" & DTEntryDate.Value & ""
    29.                   Debug.Print sSQL
    30.       oConn.Execute sSQL
    31.      
    32.       sSQL = "INSERT INTO tblStockTransFile (ProductID, EntryDate, PurchasePrice, Quantity, Reason)" & _
    33.                 "VALUES('" & txtProdID.Text & "'," & DTEntryDate.Value & ",'" & txtProdPurchasePrice.Text & _
    34.                    "','" & txtProdQTY.Text & " ','In')"
    35.                  '  Debug.Print sSQL
    36.       oConn.Execute sSQL
    37.  
    38.    
    39.     oConn.CommitTrans
    40.    
    41.   End If
    42.  
    43.   Call FillListView(lstStockMasterFile, rsStock)
    44.   Call ClearFunction(frmStockMasterFile, "TextBox")
    45.  
    46.   txtProdID.SetFocus
    47.   Exit Sub
    48.  
    49. ErrHandler:
    50.   oConn.RollbackTrans
    51.   Call msgError(Err)
    52. End Sub 'cmdSave_Click
    I have come up of something like the code below but it is still lacking. I dont have parameters yet. Am I on the right track?
    Code:
    Use MasterFile
    GO
    If EXISTS(SELECT name FROM sysobjects
    		WHERE name='StockIn')
    	DROP PROCEDURE StockIn
    GO
    
    CREATE PROCEDURE StockIn
    	@ProdID varchar(50),@EntryDate datetime,
    	@ProdPurchasePrice money, @ProdQTY numeric(18,0)
    AS
    DECLARE @errorCode int  
    INSERT tblStockTransFile (ProductID, EntryDate, PurchasePrice,Quantity)
                  VALUES(@ProdID,@EntryDate,@ProdPurchasePrice,@ProdQTY)
    SET @ErrorCode=@@ERROR
    IF (@errorCode=0)
    	RETURN (0)
    ELSE
    	RETURN (@ErrorCode)
    Last edited by Simply Me; Sep 17th, 2007 at 08:29 AM.
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  37. #37

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    Am I doing it correct?
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  38. #38
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    Have you tested it in a query window yet?

    Code:
    Exec StockIn 'xyz','2007-09-17',100,1.5
    Substitute the 'xyz' for a real product code if you like.

    Post #19 shows a better way to test with a BEGIN TRAN and ROLLBACK with a SELECT for proof of concept.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  39. #39

    Thread Starter
    PowerPoster Simply Me's Avatar
    Join Date
    Aug 2003
    Posts
    2,748

    Re: Sql Count

    i get this error "Msg 547, Level 16, State 0, Procedure StockIn, Line 7
    The INSERT statement conflicted with the FOREIGN KEY constraint "FK_tblStockTransFile_tblStockMasterFile". The conflict occurred in database "MasterFile", table "dbo.tblStockMasterFile", column 'ProductID'.
    The statement has been terminated."
    To give is always to be NOBLE...
    To received is always to be BLESSED....
    Each day strive to be NOBLE
    Each day strive to be BLESSED

    If this post has helped you. Please take time to rate it.

    >=|+|=< Simply Me >=|+|=<

    ----------------------------------------
    Connection Strings | Number Only in Textbox | Splash Screen with Progress Bar | Printing to 1/2 of perforated bond paper |
    Freeze 2005 DataGridView Column

  40. #40
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 2004
    Location
    Connecticut
    Posts
    18,263

    Re: Sql Count

    That message clearly states that the foreign key is not happy with you.

    There is no entry in the Master File yet - are you simply using a bad set of sample data??

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width