2014-12-08 177 views
0

我有一个700行的表。我想要做的是,对它执行`select * from table_name'查询,并且无论结果如何,我都希望将它存储在一个变量中,然后完成,想遍历每个记录以进行处理?我如何实现它?任何帮助?将SELECT *语句的结果赋值给变量SQL SERVER

谢谢进阶, -saurabh

+0

看起来你可以使用游标的例子。然后,再看看是否可以将数据作为一个集合而不是记录级别处理,这是一个好主意。 – 2014-12-08 07:25:20

+2

你想要什么处理?也许它可以在没有光标的情况下完成。 – 2014-12-08 07:28:31

回答

1

你想要的东西被称为cursors

光标

您使用游标来获取查询返回的行。使用查询将行检索到游标中,然后从游标中一次获取一行。

步骤

  1. 声明变量来存储列值的行。
  2. 声明包含查询的游标。
  3. 打开游标。
  4. 从光标一次取出一行并将列值存储在步骤1中声明的变量中。然后,您将对这些变量执行一些操作;如在屏幕上显示它们,在计算中使用它们等等。
  5. 关闭游标。

希望这可以帮助你cursor

+1

尝试在此处包含链接内容摘要,以便即使链接不可用,您的答案也很有用。 – 2014-12-08 07:33:08

+0

@ shree.pat18谢谢 – 2014-12-08 07:40:40

0

这里是我用来启动与

USE pubs 
GO 

-- Declare the variables to store the values returned by FETCH. 
DECLARE @au_lname varchar(40), @au_fname varchar(20) 
DECLARE authors_cursor CURSOR FOR 
SELECT au_lname, au_fname FROM authors 
--WHERE au_lname LIKE 'B%' 
ORDER BY au_lname, au_fname 

OPEN authors_cursor 

-- Perform the first fetch and store the values in variables. 
-- Note: The variables are in the same order as the columns 
-- in the SELECT statement. 

FETCH NEXT FROM authors_cursor 
INTO @au_lname, @au_fname 

-- Check @@FETCH_STATUS to see if there are any more rows to fetch. 
WHILE @@FETCH_STATUS = 0 
BEGIN 

-- Concatenate and display the current values in the variables. 
PRINT @au_fname 

-- This is executed as long as the previous fetch succeeds. 
FETCH NEXT FROM authors_cursor 
INTO @au_lname, @au_fname 
END 

CLOSE authors_cursor 
DEALLOCATE authors_cursor 
GO 
相关问题