如何在不使用 FETCH .. INTO 的情况下访问游标列

发布于 2024-08-02 10:47:12 字数 489 浏览 2 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

海拔太高太耀眼 2024-08-09 10:47:12

不,如果您想将游标中的值存储在局部变量中而不是将它们返回给客户端,则必须这样做。

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.

乄_柒ぐ汐 2024-08-09 10:47:12

如果这是你的整个程序(来自OP问题):

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;

那么你可以执行以下操作来返回两列的结果集,不需要游标:

SELECT top 1 col1, col2 
FROM table;

if this is your entire porcedure (right from OP question):

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;

then you can just do the following to return a result set of the two columns, no cursor necessary:

SELECT top 1 col1, col2 
FROM table;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文