SQL Server 游标数据作为存储过程的结果
我有一个存储过程
DECLARE cursor FOR SELECT [FooData] From [FooTable];
OPEN cursor ;
FETCH NEXT FROM cursor INTO @CurrFooData;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @CurrFooData AS FooData;
INSERT INTO Bar (BarData) VALUES(@CurrFooData);
FETCH NEXT FROM cursor INTO @CurrFooData;
END;
CLOSE cursor
DEALLOCATE cursor
但结果我有很多表,而不是一个。如何返回一张包含“FooData”列和所有“@CurrFooData”行的表?
I have a stored procedure
DECLARE cursor FOR SELECT [FooData] From [FooTable];
OPEN cursor ;
FETCH NEXT FROM cursor INTO @CurrFooData;
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @CurrFooData AS FooData;
INSERT INTO Bar (BarData) VALUES(@CurrFooData);
FETCH NEXT FROM cursor INTO @CurrFooData;
END;
CLOSE cursor
DEALLOCATE cursor
But in result I have a lot of tables, not one. How can I return one table with 'FooData' column and all '@CurrFooData' rows?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
德米特里,我认为你真的应该尝试一起摆脱那个光标。在第二个示例中,您选择了两个字段
FooData1
和FooData2
,但最终,您只插入了值......您可以重写第二个查询很容易 - 就像:
这就是你的整个光标和所有事情真正在做的事情。
尽量避免使用游标 - 99% 的时间,它们是不需要的 - 开始考虑数据集 - 不要坚持 SQL 中的过程循环和游标 - 这不是一个很好的匹配!
如果您需要输出刚刚插入的内容,请使用
OUTPUT
子句:Dmitry, I think you should really try to get rid of that cursor all together. In the second example, you're selecting two fields
FooData1
andFooData2
, but in the end, you're only ever inserting of the values....You could rewrite that second query easily - something like:
That's all that your entire cursor and everything is really doing.
Try to avoid cursors at all costs - 99% of the time, they're not needed - start to think in SETS of data - do not stick to procedural loops and cursor in SQL - that's just not a good match!
If you need to output what you've just inserted, use the
OUTPUT
clause:是不是要输出刚刚插入的数据?如果是这种情况,并且您使用的是 SQL Server 2005 之前的 SQL Server 版本,那么您可以将所需的值填充到临时表中,如下所示:
这种方法的缺点是由于临时表的原因,它可能会导致每次运行存储过程时重新编译。
如果您使用的是 SQL Server 2000+,您可以仅在表变量中执行与上面相同的操作:
如果您使用的是 SQL Server 2005+,您可以使用 OUTPUT 子句,如下所示:
Is it that you want to output the data you just inserted? If that is the case, and if you are using a version of SQL Server prior to SQL Server 2005, then you can stuff the values you want into a temp table like so:
The downside to this approach is that it will likely cause a recompile on your stored procedure each time it is run because of the temp table.
If you are using SQL Server 2000+ you could do the same as above only in a table variable:
If you are using SQL Server 2005+, you can use the OUTPUT clause like so: