Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select a row and store in a SQL variable

So, I'm writing this Stored Proc and I really suck at SQL.

My Question to you guys is:

Can I select an entire row and store it in a variable?

I know I can do something like:

declare @someInteger int
select @someInteger = (select someintfield from sometable where somecondition)

But can I select the entire row from sometable and store it in a variable?

like image 331
EJC Avatar asked Sep 22 '10 21:09

EJC


People also ask

How do you store a row in a variable in SQL?

DECLARE @A int, @B int SELECT @A = Col1, @B = Col2 FROM SomeTable WHERE ... Another, potentially better, approach would be to use a table variable: DECLARE @T TABLE ( A int, B int ) INSERT INTO @T ( A, B ) SELECT Col1, Col2 FROM SomeTable WHERE ... You can then select from your table variable like a regular table.

Can we store query in variable in SQL?

Yup, this is possible of course.

How do you assign a value to a row in SQL?

A row value can be assigned to a variable of type row by using a SELECT INTO statement, a VALUES INTO statement, or a FETCH INTO statement. The field values of the source row value must be assignable to the field values of the target row variable.


2 Answers

You can select the fields into multiple variables:

DECLARE @A int, @B int  SELECT   @A = Col1,   @B = Col2 FROM SomeTable WHERE ... 

Another, potentially better, approach would be to use a table variable:

DECLARE @T TABLE (   A int,   B int ) INSERT INTO @T ( A, B ) SELECT   Col1,   Col2 FROM SomeTable WHERE ... 

You can then select from your table variable like a regular table.

like image 178
Bennor McCarthy Avatar answered Sep 29 '22 11:09

Bennor McCarthy


You could create a table variable that matches your table schema and store the single row in it:

declare @myrow table(field0 int,field1 varchar(255))
insert into @myrow
select field0,field1 from mytable where field0=1
like image 25
brendan Avatar answered Sep 29 '22 13:09

brendan