简体   繁体   中英

store values from select query to variables

I'd like to store values onto declared variables from a select query, but the problem here is that my select query returns multiple rows. See example below

select Col1
from Table1 where Col1 NOT IN (select Col1 from Table2) 
and Col3 >=8


------------------
result
73
74

declare @temp1 int
declare @temp2 int

I essentially want @temp1 to hold 73 and @temp2 hold 74 and so fort...

Any ideas on how to achieve this will be of great help. Please let me know if you need any more explanation.

Thanks in advance, Gagan

I think you are looking for cursors .

Here is a nice link explians it.

I would say you should use table variable (or maybe temporary table) for storing multiple values.

declare @tab table
    (
        col1 int
    );

with myTab as
(
    Select 1 col
    Union All 
    Select 2
    Union All
    Select 3
)
Insert Into @tab 
    Select Col 
    From MyTab

Select * From @tab

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