Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign single variable a multiple rows using Select query in stored procedure

Tags:

sql-server

My query is to assign single variable a multiple rows using Select query in stored procedure For example: I get 10(say 1 to 10) employee ids from from Employee table declare @id int

select @id =EmpId from Employee

select @id

This will return 10 rows(i.e.Employee id , suppose there are 10 rows in a table) now my question is how i will get this all rows in a single variable and use that employee id one by one to perform some calculation.

like image 283
Vivekh Avatar asked Jul 05 '11 13:07

Vivekh


People also ask

How do you assign a row to a variable 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.

How do you set a variable in a SELECT statement in SQL Server?

When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement. This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.


2 Answers

You cannot insert 10 records into one variable.
What you can do however is:

declare @id table (id int)

insert into @id (id)
select EmpId from Employee

select * from @id

What we have done here is create a table variable, which inserts 1 through 10 as seperate rows. You can now do whatever you want with the table.

like image 141
AndrewBay Avatar answered Jan 04 '23 10:01

AndrewBay


Try this:

 declare @tmp table(EmpId int)

    insert into @tmp
    select EmpId From Employee

update Employee
set IsActive = 1
where EmpID in (
Select EmpId from @tmp)
like image 28
Ovais Khatri Avatar answered Jan 04 '23 09:01

Ovais Khatri