while循環的語句格式:
while(判斷條件語句){
循環體語句;
}
擴展格式:
初始化語句;
while(判斷條件語句){
循環體語句;
控制條件語句;
}
方法1:使用臨時表
使用臨時表,和游標類似,同時將大量的數據存儲到內存中,但是隨着遍歷的進行,臨時表的數據量越來越小,可以相當程度的降低內存的消耗,但是需要不停的與table表做交互
-- 創建臨時表
SELECT NID,CROWID,LXBM,LDXLH
INTO #T_LD
FROM TMPTABLE1
-- 聲明變量
DECLARE
@LDBM AS NVARCHAR(20),
@LDXLH AS NVARCHAR(20),
@LXBM AS NVARCHAR(20),
@CROWID AS NVARCHAR(80),
--@sqlstr varchar(1000),
@NID INT;
WHILE EXISTS(SELECT NID FROM #T_LD)
BEGIN
-- 也可以使用top (1)
SET ROWCOUNT 1 --在返回指定的行數之后停止處理查詢,只顯示第1條記錄
SELECT @LXBM=substring(CROWID,1,4),@CROWID=LXBM+'審批流',@nid=nid FROM #T_LD;
print(@nid)
UPDATE tmpTable1 SET CROWID=@CROWID where @nid=NID and CrowId='';
UPDATE tmpTable1 SET LXBM= @LXBM where @nid=NID and LXBM='';
SET ROWCOUNT 0 --關閉該選項,返回所有的行
DELETE FROM #T_LD WHERE NID=@nid;
END
DROP TABLE #T_LD
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--判斷零時表是否存在,如果存在刪除--
if exists (select * from tempdb.dbo.sysobjects where id = object_id(N'tempdb..#tempcitys') and type='U')
drop table #tempcitys
go
--創建零時表
create table #tempcitys
(
id int primary key identity(1,1),
name nvarchar(50)
)
go
--插入數據
insert into #tempcitys(name) values('上海');
insert into #tempcitys(name) values('杭州');
insert into #tempcitys(name) values('蘇州');
go
--遍歷零時表
declare @city_name nvarchar(50)
while exists(select name from #tempcitys)
begin
set rowcount 1
select @city_name=name from #tempcitys
print @city_name
set rowcount 0
delete from #tempcitys where name = @city_name
--print @city_name
end
方法2:使用索引表
索引表和臨時表的操作類似;唯一區別在於在建立臨時表是,添加一個索引,然后通過此索引從表中取數據;效率上有所提升,但是增加了變量的輸出,代碼如下
--方法3:使用索引表
SELECT * FROM TMPTABLE
SELECT * FROM TMPTABLE1
--創建臨時表
IF EXISTS(Select Name From Sysobjects Where Name='tmpTable1')
DROP table tmpTable1 --存在則刪除
create table tmpTable1(
NID int primary key identity(1,1), --主鍵,自增
CrowId nvarchar(90),
LXBM nvarchar(20),
LDXLH nvarchar(6),
)
--插入數據
insert into tmpTable1(CrowId,LXBM,LDXLH)
select CrowId,LXBM,LDXLH from tmpTable
-- 聲明變量
DECLARE
@index int,
@countNum int,
@LDBM AS NVARCHAR(20),
@LDXLH AS NVARCHAR(20),
@LXBM AS NVARCHAR(20),
@CROWID AS NVARCHAR(80),
@nid int;
--select * from tmpTable1;
select @countNum=count(1) from tmpTable1;
set @index=0;
--遍歷
while @index<@countNum
begin
set @index=@index+1;
select @LXBM=substring(CROWID,1,4),@CROWID=LXBM+'審批流',@nid=nid from tmpTable1 where NID=@index
UPDATE tmpTable1 SET CROWID=@CROWID where @nid=NID and CrowId='';
UPDATE tmpTable1 SET LXBM= @LXBM where @nid=NID and LXBM='';
-- UPDATE tmpTable1 SET LDBM= @LXBM+' '+@LDXLH WHERE CROWID=@CROWID;
end
--刪除臨時索引表
DROP table tmpTable