0

I'm writing the following SQL statement in-order to get a sum value from a specific table using VB.NET. But, I keep getting the following error

itCode is a variable

Dim strSql As String = "SELECT sum(purchase_qty) FROM TB_STOCK WHERE it_code='" & itCode & "' AND added_date BETWEEN #07/21/2020 00:00:00# AND #07/21/2020 23:59:59#"

error : System.Data.SqlClient.SqlException: 'Incorrect syntax near '00'.'

2 Answers 2

1

I'm fairly certain that SQL Server doesn't understand date literals like that. That would work for Access but different databases require different syntax. You should use text literals in yyyy-MM-dd format:

"' AND added_date BETWEEN '2020-07-21 00:00:00' AND '2020-07-21 23:59:59'"

That said, I'm guessing that you're going to have to vary those dates at some point, so you probably ought to be using parameters. You definitely should be using a parameter for the it_code value, e.g.

Dim sql = "SELECT sum(purchase_qty) FROM TB_STOCK WHERE it_code = @it_code AND added_date BETWEEN @added_date_start AND @added_date_end"
Dim command As New SqlCommand(sql, connection)

With command.Parameters
    .Add("@it_code", SqlDbType.VarChar, 50).Value = itCode
    .Add("@added_date_start", SqlDbType.DateTime).Value = myDate
    .Add("@added_date_end", SqlDbType.DateTime).Value = myDate.AddDays(1).AddSeconds(-1)
End With

I agree with Rodney Ellis about not using BETEWEEN too. I would do it like this:

Dim sql = "SELECT sum(purchase_qty) FROM TB_STOCK WHERE it_code = @it_code AND added_date >= @added_date_start AND added_date < @added_date_end"
Dim command As New SqlCommand(sql, connection)

With command.Parameters
    .Add("@it_code", SqlDbType.VarChar, 50).Value = itCode
    .Add("@added_date_start", SqlDbType.DateTime).Value = myDate
    .Add("@added_date_end", SqlDbType.DateTime).Value = myDate.AddDays(1)
End With

The last two examples both assume that myDate already has the time zeroed. If it doesn't, you can use myDate.Date.

Sign up to request clarification or add additional context in comments.

1 Comment

I was using this statement inside of a function. I passed the date values as parameters. But, I can see that, this is the better method and I'm going to use it. thank you again.
1
Dim strSql As String = "SELECT sum(purchase_qty) FROM TB_STOCK 
WHERE it_code='" & itCode & "' AND added_date BETWEEN '2020-07-20 00:00:00' AND '2020-07-21 23:59:59'"

Also, don't use BETWEEN - https://www.mssqltips.com/sqlservertutorial/9316/sql-server-between-dates-issue/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.