简体   繁体   English

将选择查询中的值存储到变量中

[英]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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM