[2008] using VB variables in SQL statements
I want to use VB variables in SQL code...
Dim varCount As Integer = 3
Dim sqlCmd As New SqlCommand("SELECT test FROM MyTable WHERE id = {varCount}")
The sql syntax may be wrong, because I typed this by hand, but I want to know how I can use varCount in my SQL statement...
Can anyone help me?
Thanks
Re: [2008] using VB variables in SQL statements
vb.net Code:
Dim sqlCmd As New SqlCommand("SELECT test FROM MyTable WHERE id = " & varCount & ")"
Re: [2008] using VB variables in SQL statements
Re: [2008] using VB variables in SQL statements
That is for a numeric value.
FYI: If varcount was a string, or text value, it would look like this
vb.net Code:
Dim sqlCmd As New SqlCommand("SELECT test FROM MyTable WHERE id = '" & varCount & "')"
Re: [2008] using VB variables in SQL statements
Re: [2008] using VB variables in SQL statements
While Hack's advice will do the job in this case and in others too, I have to advise following best practice and use parameters whenever inserting values into SQL statements:
vb.net Code:
Dim command As New SqlCommand("SELECT MyColumn FROM MyTable WHERE ID = @ID", connection
command.Parameters.AddWithValue("@ID", id)
By using parameters you generally make your code more readable, less error-prone and more secure. In this case it may make no significant difference but I think it's good to do things the "proper" way all the time unless there's a genuine reason for doing otherwise.
Re: [2008] using VB variables in SQL statements
Thanks jm, I'll do that.
Cheers