Search code examples
sql-servervb.netsyntaxsqlparameter

Incorrect syntax near SqlParameter


I have this code

Dim q = New SqlCommand("SELECT * FROM [ddddd] WHERE ([Day] >= %XX ) AND ([Day] <= %YY )")
q.Parameters.Add(New SqlParameter("XX", rangeFrom.Value))
q.Parameters.Add(New SqlParameter("YY", rangeTo.Value))

q.Connection = dbc

Dim rd = q.ExecuteReader()
' ...

It throws a SqlException on the

Dim rd = q.ExecuteReader()

line with message

Incorrect syntax near 'XX'

Why?


Solution

  • SQL Server parameters need to be prefixed with a @ (not a % as you've used it):

    SELECT * 
    FROM [ddddd] 
    WHERE [Day] >= @XX AND [Day] <= @YY
    

    and then also use the leading @ when declaring the parameters:

    q.Parameters.Add(New SqlParameter("@XX", rangeFrom.Value))
    q.Parameters.Add(New SqlParameter("@YY", rangeTo.Value))