Sql Server For循環


Sql Server 循環實現

標號不利用游標

declare @begin int
declare @loopIndex int
declare @SN nvarchar(50)
declare @Ith float
set @begin=1
select @loopIndex = COUNT([Test].dbo.QXIth.SN) from dbo.QXIth --循環的最大次數
begin
	while @begin<@loopIndex
		begin
			 select @SN=temp.SN,@Ith = temp.Ith from (select *,ROW_NUMBER() over(order by SN) as 行數 from [Test].dbo.QXIth)as temp where temp.行數=@begin
			 if exists(select 1 from [Test].dbo.奇芯 where 序列號=@SN)
				begin
				update dbo.奇芯 set 門限電流 = @Ith where dbo.奇芯.序列號 =@SN;
				
				end
			else begin
				insert into dbo.奇芯 (序列號,門限電流)values(@SN,@Ith)
				end
			set @begin=@begin+1;
			continue;
		end
end
print @loopIndex

游標

declare @SN nvarchar(50)
declare @Ith float
declare @num int
set @num=0
declare cursorTemp  cursor for select SN,Ith from [Test].[dbo].[QXIth]
open cursorTemp
fetch next from cursorTemp into @SN,@Ith 
while @@FETCH_STATUS=0--這里計數會多一個,
	begin
		if exists(select 1 from [Test].[dbo].[奇芯] where [Test].[dbo].[奇芯].[序列號]=@SN)
			begin
			update dbo.奇芯 set 門限電流 = @Ith where dbo.奇芯.序列號 =@SN;
			set @num =@num+1
			end
		else begin
			insert into dbo.奇芯 (序列號,門限電流)values(@SN,@Ith)
		end
		FETCH NEXT FROM  cursorTemp INTO @SN,@Ith
	end
close cursorTemp
DEALLOCATE cursorTemp
print @num


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM