8

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.

1
  • This isn't possible, see the Answers below, but do take good note that this action will succeed by assigning the last value of the results to the variable, and does not produce an error. So, either know that this is how it works, or use a TOP x or other WHERE to return one row, or use the SET command. Commented Jan 17, 2013 at 18:31

4 Answers 4

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi small help in query result it gives me which is perfect 1 2 3 4 5 i want these empid to be use one by one set TempId1=Empid -- (this time should be 1) set TempId3 = Empid -- (this time it should be 3) and so on..
2

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)

Comments

2

You can squeeze each of the rows into one variable, but as you want to process the output one by one I would recommend avoiding this approach:

/*
 * Remember that NULL + any string = NULL.
 * Provide the concat var with a default value.
 */
DECLARE @ConCat         VARCHAR(255) = '';  
DECLARE @SampleTable    TABLE
    (
        Value   VARCHAR(5)
    )
;

-- Populate the sample table.
INSERT INTO @SampleTable (Value)
    VALUES
        ('a'),
        ('b'),
        ('c')
;

-- Concatenate the values into one string.
SELECT
    @ConCat = @ConCat + Value
FROM
    @SampleTable
;


-- Return the concatenated string
SELECT
    @ConCat
;

Comments

0

If processing rows one by one is necessary, cursor will be useful.

Here's a tutorial for how to use a cursor.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.