Hitesh Thakur
Hitesh Thakur

Reputation: 47

How to put column values in variables in SQL Server

I have a SQL Server table #SqlData with the following column splitdata.

splitdata
---------
BB10_1_X
4759
566549

I want to store these 3 column values into 3 different variables. Please help me as I am a beginner and I don't know how to do it..

Upvotes: 0

Views: 80

Answers (1)

rory.ap
rory.ap

Reputation: 35260

You can declare variables like this:

DECLARE @Var AS VARCHAR(MAX) 

And you can assign them using a select statement like this:

SELECT @Var=MyColumn 
FROM MyTable 
WHERE <My Condition>

There are plenty of resources on TSQL if you google it.

In your situation, if you're sure you will have exactly three rows, you can use three separate select statements:

DECLARE @Var1 AS VARCHAR(MAX), @Var2 AS VARCHAR(MAX), @Var3 AS VARCHAR(MAX)

SELECT @Var1=MyColumn 
FROM MyTable 
WHERE <My Condition That Returns First Row>

SELECT @Var2=MyColumn 
FROM MyTable 
WHERE <My Condition That Returns Second Row>

SELECT @Var3=MyColumn 
FROM MyTable 
WHERE <My Condition That Returns Third Row>

Upvotes: 2

Related Questions