简体   繁体   中英

How can I use a variable inside a SELECT statement?

I am a newbie to SQL. The problem which I am facing is, I want to select a particular name John from the customer table, but I am storing John in a string called var_name . Now is there any way that I can use this variable name in the select statement instead of writing John?

sorry i forgot to explain the question in depth,

i am having a table which contains details of the customers, among that customer name is one of the coloumn, so when user clicks on any particular name from customer name coloumn that name is getting stored in the variable called var_name and i want that particular customer name's customer id, this is the issue which i didnt mention in the question above. So i want that random value clicked in the coloumn should get replace in the SELECT statement. your query will work if the user clicks on John, i want a general query for the above issue

Here is an example

SELECT var_name -- this is what I've used, is there any other way to accomplish this?
FROM Customer
Where Customer_ID = '1234';

so please help me out to solve this issue.

Thank You!

Wrap a single-value select in brackets to use its value in another query:

select something
from sometable
where somecolumn = (SELECT name FROM Customer Where Customer_ID = '1234')

In case you are using SQL server, You can actually declare your var_name:

DECLARE @var_name nvarchar(50) SET @var_name = (SELECT "something" FROM Customer WHERE Customer_ID = '1234') from here, you can do whatever you want with @var_name

I hope this is the what you are asking for,

SqlConnection con = new SqlConnection("Your connection goes here");
con.Open();
SqlCommand cmd = new SqlCommand("Select name from customer where customerid = '1234'",con);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
  string var_name = dr.GetString(0);
}
con.Close();

This is one of the way that you can the store the values from database to your string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM