Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I can not find a WORKING example using a variable data element in the sql select from where clause.

example select * from table where fielda = "123" is not what I want to do.

string myselection = "123";

select * from table where fielda = myselection is what I want

I am using C# and visual studio 2008 and sql server 2008.

thanks.

[email removed for your protection]

[Modified: First, I added the C# tag...second, I removed your email...if someone posts a response to this, you'll get an email...posting your email only servers to help spammers know where to send stuff]
Posted
Updated 30-Mar-10 10:41am
v2

One simpler method for it looks like you need:
SQL
SET @mySelection = '123'
SELECT * FROM myTable WHERE fielda = @mySelection
 
Share this answer
 
ok...so do

C#
string SQL = "SELECT * FROM table WHERE fielda='" & myselection & "';"


or

C#
SqlCommand nonqueryCommand = thisConnection.CreateCommand();

nonqueryCommand.CommandText = "SELECT * FROM table WHERE fielda=@fielda;";
nonqueryCommand.Parameters.Add("@fielda", SqlDbType.VarChar, 30);


[Updated: sorry, I missed a parameter in the Add. It should read
C#
nonqueryCommand.Parameters.Add("@fielda",SqlDbType.Int).Value = 123;
//or something similar


And what's with the downvoting?]
 
Share this answer
 
v3
Comments
CS2011 19-May-11 2:27am    
Not sure why some one will down vote this answer.Seems good enough to me. my 5+
Use this

string SQL = @"SELECT * FROM table WHERE fielda='" + myselection + "'"


This sould work....
 
Share this answer
 
select * from table where fielda = '" & myselection & "' ";

generates the following error that I can not get rid of.

field initializer cannot reference the non-static field, method, or property 'Client_Maintenance.AddressLoad.myselection' C:\TARE SYSTEM\Client Maintenance\AddressLoad.cs 49 164 Client Maintenance

I appreciate your help.
 
Share this answer
 
string myselection = "123";

// fielda is char,varchar,nvarchar,etc...
string SQL = String.Format("select * from table where fielda = '{0}'", myselection); 

// fielda is numeric...
string SQL = String.Format("select * from table where fielda = {0};", myselection);
 
Share this answer
 
Comments
Member 13353325 3-Oct-17 9:50am    
how to pass multiple string variable in '" format in sql where clouse

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900