SQL Server的while迴圈雖然不常使用,但是當有資料需要批次讀取和運算時,這時候的while迴圈就相當的好用,下面就來分享在SQL Server下使用while迴圈的方法
語法:
--定義迴圈參數
DECLARE
@tn INT, --執行次數
@n INT --當前次數
--設定迴圈參數
SET @tn = 10 --執行次數
SET @n =1 --當前次數
--執行WHILE迴圈
WHILE @n <= @tn --當前次數 <= 執行次數
BEGIN
--這裡放要執行的迴圈SQL
Print '目前執行次數是第 '+convert(varchar,@n)+' 次'
SET @n = @n + 1 --當前次數 + 1
END

實作:

語法:
--建立暫存table
CREATE TABLE #tmp
(
id INT, --編號
Valuestr varchar(2) --內容
)
--給值
insert into #tmp select 1,'鼠'
insert into #tmp select 2,'牛'
insert into #tmp select 3,'虎'
insert into #tmp select 4,'兔'
insert into #tmp select 5,'龍'
insert into #tmp select 6,'蛇'
insert into #tmp select 7,'馬'
insert into #tmp select 8,'羊'
insert into #tmp select 9,'猴'
insert into #tmp select 10,'雞'
insert into #tmp select 11,'狗'
insert into #tmp select 12,'豬'
--定義迴圈參數
DECLARE
@tn INT, --執行次數
@n INT, --當前次數
@str varchar(36)
--設定迴圈參數
SET @tn = 12 --執行次數
SET @n =1 --當前次數
--執行WHILE迴圈
WHILE @n <= @tn --當前次數 <= 執行次數
BEGIN
select @str = isnull(@str,'') + Valuestr from #tmp where id = @n
SET @n = @n + 1 --當前次數 + 1
END
select 十二生肖 = @str

實作:
