我的情景略有不同。我在存储过程中所做的是
创建临时表并使用“光标”
插入行Create Table #_tempRawFeed
(
Code Int Identity,
RawFeed VarChar(Max)
)
使用游标
在临时表中插入数据 Set @GetATM = Cursor Local Forward_Only Static For
Select DeviceCode,ReceivedOn
From RawStatusFeed
Where C1BL=1 AND Processed=0
Order By ReceivedOn Desc
Open @GetATM
Fetch Next
From @GetATM Into @ATM_ID,@Received_On
While @@FETCH_STATUS = 0
Begin
Set @Raw_Feed=@ATM_ID+' '+Convert(VarChar,@Received_On,121)+' '+'002333'+' '+@ATM_ID+' : Bills - Cassette Type 1 - LOW '
Insert Into #_tempRawFeed(RawFeed) Values(@Raw_Feed)
Fetch Next
From @GetATM Into @ATM_ID,@Received_On
End
现在必须使用另一个Cursor
处理Temp Table中的每一行DECLARE @RawFeed VarChar(Max)
DECLARE Push_Data CURSOR FORWARD_ONLY LOCAL STATIC
FOR SELECT RawFeed
FROM #_tempRawFeed
OPEN Push_Data
FETCH NEXT FROM Push_Data INTO @RawFeed
WHILE @@FETCH_STATUS = 0
BEGIN
/*
What Should i write here to retrieve each row one at a time ??
One Row should get stored in Variable..in next iteration previous value should get deleted.
*/
FETCH NEXT FROM Push_Data INTO @RawFeed
END
CLOSE Push_Data
DEALLOCATE Push_Data
Drop Table #_tempRawFeed
我应该在BEGIN中写一下每次检索一行? One Row应该存储在Variable..in下一次迭代中,之前的值应该被删除。
答案 0 :(得分:0)
关于你的上一个问题,如果你在最后一个光标中真正打算做的是将RawFeed列值连接成一个变量,则根本不需要游标。您可以使用以下内容(根据您的SQL小提琴代码改编):
CREATE TABLE #_tempRawFeed
(
Code Int IDENTITY
RawFeed VarChar(MAX)
)
INSERT INTO #_tempRawFeed(RawFeed) VALUES('SAGAR')
INSERT INTO #_tempRawFeed(RawFeed) VALUES('Nikhil')
INSERT INTO #_tempRawFeed(RawFeed) VALUES('Deepali')
DECLARE @RawFeed VarChar(MAX)
SELECT @RawFeed = COALESCE(@RawFeed + ', ', '') + ISNULL(RawFeed, '')
FROM #_tempRawFeed
SELECT @RawFeed
DROP TABLE #_tempRawFeed
更多关于将不同的行值连接到一个字符串:Concatenate many rows into a single text string?
我很确定你也可以避免使用第一个游标。请避免使用游标,因为真的伤害了性能。使用基于集合的操作可以实现相同的结果。