How to Insert a Variable into an SQL String

I have an SQL statement like this
strSQL = "SELECT  MyField FROM MyTable WHERE PID = 301"

I wish to provide the Value for PID in the above statement through a variable and I wish to know the correct way of doing it if at all it is possible:

I have tried doing it like this:

Dim MyVariable as String
MyVariable as “Peter Smith”

strSQL = "SELECT  MyField FROM MyTable WHERE PID = MyVariable"

How ever when I use the above approach I get an error message in my Code. I wish to know what would be the correct method for inserting a Variable in an SQL statement like the above.
Thank you for your help.

LVL 1
FaheemAhmadGulAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

tomazsrCommented:
Hi,

try this:

strSQL = "SELECT  MyField FROM MyTable WHERE PID = '"+MyVariable+"'"
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sridharthirunagariCommented:
Try this..

strSQL = "SELECT  MyField FROM MyTable WHERE PID = @MyVariable"
0
Lee SavidgeCommented:
If this is from the VB side, then if PID is a numeric value in SQL you need to do:

strSQL = "select myfield from mytable where pid = " & myvariable

if PID is a string value in SQL you need to do this:

strSQL = "select myfield from mytable where pid = '" & myvariable & "'"

Lee
0
YohanFCommented:
Also when assigning value to MyVariable, it should be

MyVariable = “Peter Smith”
0
FaheemAhmadGulAuthor Commented:
As both solutions are correct and came within a very short span of time, I am accepting both and splitting the points equally. I hope this is considered fair. Many thanks for your help. I am very grateful. Regards
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.