while 循环 T-SQL 中的 Union select 语句
我正在尝试使用游标动态生成结果集。以下是代码,
DECLARE @ MilestoneName VARCHAR(100),
@MilestoneSts VARCHAR(100),
@ProjectPre VARCHAR(10),
@ProjectID VARCHAR(10),
@Center VARCHAR(20),
@CenterPre VARCHAR(20),
@Source VARCHAR(20),
@Actual INT;
SET @MilestoneName = null;
SET @MilestoneSts = null;
SET @ProjectPre = null;
SET @CenterPre = null;
DECLARE s_cursor CURSOR FOR
SELECT ProjectID, Center, Source, Actual
FROM #MILESTONE
OPEN s_cursor
FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @@FETCH_STATUS sts, @ProjectID PID, @Center Center, @Source Source, @Actual Actual
FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual
END
CLOSE s_cursor
DEALLOCATE s_cursor
但是使用它我可以生成 79 个单行结果,但我想将所有这些行合并为一个结果。任何可能的解决方案将受到高度赞赏。
I'm trying to use cursors to dynamically produce a result set. following is the code
DECLARE @ MilestoneName VARCHAR(100),
@MilestoneSts VARCHAR(100),
@ProjectPre VARCHAR(10),
@ProjectID VARCHAR(10),
@Center VARCHAR(20),
@CenterPre VARCHAR(20),
@Source VARCHAR(20),
@Actual INT;
SET @MilestoneName = null;
SET @MilestoneSts = null;
SET @ProjectPre = null;
SET @CenterPre = null;
DECLARE s_cursor CURSOR FOR
SELECT ProjectID, Center, Source, Actual
FROM #MILESTONE
OPEN s_cursor
FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @@FETCH_STATUS sts, @ProjectID PID, @Center Center, @Source Source, @Actual Actual
FETCH NEXT FROM s_cursor INTO @ProjectID, @Center, @Source, @Actual
END
CLOSE s_cursor
DEALLOCATE s_cursor
However using that I'm able to produce 79 results of single rows but I want to union all those rows into one result.. any possible solution will be highly appreciated..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是检查一下,为什么要使用光标呢?
这个存储过程可以被替换为
但也许我在这里遗漏了一些东西?
如果您在代码中遗漏了逻辑,请查看这篇文章: 多语句表值函数与内联表值函数
GJ
just checking, why are you using a cursor for this?
This sproc could be replaced by just saying
But maybe I'm missing somehting here?
If there's logic you left out in your code look at this post: Multi-statement Table Valued Function vs Inline Table Valued Function
GJ