|
-
Feb 3rd, 2008, 03:37 AM
#1
Thread Starter
Frenzied Member
[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
Last edited by Icyculyr; Feb 3rd, 2008 at 03:54 AM.
-
Feb 3rd, 2008, 03:38 AM
#2
Re: [2008] using VB variables in SQL statements
vb.net Code:
Dim sqlCmd As New SqlCommand("SELECT test FROM MyTable WHERE id = " & varCount & ")"
-
Feb 3rd, 2008, 03:44 AM
#3
Thread Starter
Frenzied Member
Re: [2008] using VB variables in SQL statements
-
Feb 3rd, 2008, 06:00 AM
#4
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 & "')"
-
Feb 3rd, 2008, 06:05 AM
#5
Thread Starter
Frenzied Member
Re: [2008] using VB variables in SQL statements
-
Feb 3rd, 2008, 06:23 AM
#6
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.
-
Feb 3rd, 2008, 06:44 AM
#7
Thread Starter
Frenzied Member
Re: [2008] using VB variables in SQL statements
Thanks jm, I'll do that.
Cheers
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|