SQL 語句對每一行進行循環操作的幾種方法
1、游標
Declare @SN varchar(16) --變量
Declare iCursor Cursor For --游標
select Distinct SNum from Table1 where zd1 like '%test%'
Open iCursor --打開游標
FETCH Next from iCursor Into @SN--用來對每一行來進行循環操作
WHILE @@FETCH_STATUS = 0
Begin
--此處對每一行要進行的操作的代碼
Fetch Next from iCursor into @SN
END
CLOSE iCursor --關閉游標
DEALLOCATE iCursor
2、IDENTITY
select * from Table1 where zd1 like '%test%'
select zd2,IDENTITY(INT,1,1) AS RNum
into #TempSN --插入臨時表
from Table1
where zd1 like '%test%'
ORDER BY zd2
Declare @maxRow int --用來獲得最大的 行數
Declare @rowNo int
Select @maxRow=max(RNum) from #TempSN
set @rowNo=1
While @rowNo<=@maxRow --用來對每一個行來進行循環操作
Begin
--此處對每一行要進行的操作的代碼
Set @rowNo=@rowNo+1
End
Drop Table #TempSN--清除臨時表
3、RowNumber (SQL 2005 以上含版本支持)
select * from Table1 where zd1 like '%test%'
select zd2,ROW_NUMBER() OVER(ORDER BY zd2) AS RowNumber
into #TempSN --插入臨時表
from Table1
where zd1 like '%test%'
Declare @maxRow int --用來獲得最大的rowNumber
Declare @rowNo int
Select @maxRow=max(rownumber) from #TempSN
set @rowNo=1
While @rowNo<=@maxRow --用來對每一個rowNumber來進行循環操作
Begin
--此處對每一行要進行的操作的代碼
Set @rowNo=@rowNo+1
End
Drop Table #TempSN--清除臨時表
創建時間:2020.10.15 更新時間: