如何在不使用 FETCH .. INTO 的情况下访问游标列
我正在使用 SQL Server 构建存储过程,并且使用游标循环执行 select 语句
我按如下方式定义游标:
DECLARE @c_col1 varchar(max);
DECLARE @c_col2 varchar(max);
DECLARE c as CURSOR FOR
SELECT col1, col2
FROM table;
OPEN c;
FETCH NEXT FROM c INTO
@c_col1, @c_col2;
SELECT @c_col1, @c_col2;
是否有一种方法无需声明变量即可访问游标的列每列并在 FETCH 子句中使用 INTO?换句话说,是否可以使用:
DECLARE c as CURSOR FOR
SELECT col1, col2
FROM table;
OPEN c;
FETCH NEXT FROM c;
SELECT c.col1, c.col2;
I'm using SQL Server to build stored procedures, and I'm using cursors to loop through a select statement
I'm defining the cursor as follow:
DECLARE @c_col1 varchar(max);
DECLARE @c_col2 varchar(max);
DECLARE c as CURSOR FOR
SELECT col1, col2
FROM table;
OPEN c;
FETCH NEXT FROM c INTO
@c_col1, @c_col2;
SELECT @c_col1, @c_col2;
Is there a way to access the columns of the cursor without a need to declare variables for each column and to use INTO in FETCH clause? In other words, is it possible to use:
DECLARE c as CURSOR FOR
SELECT col1, col2
FROM table;
OPEN c;
FETCH NEXT FROM c;
SELECT c.col1, c.col2;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,如果您想将游标中的值存储在局部变量中而不是将它们返回给客户端,则必须这样做。
No, you have to do it that way if you want to store the values from the cursor in local variables instead of returning them back to the client.
如果这是你的整个程序(来自OP问题):
那么你可以执行以下操作来返回两列的结果集,不需要游标:
if this is your entire porcedure (right from OP question):
then you can just do the following to return a result set of the two columns, no cursor necessary: