WHILE

  • 619
  • 0
  • 2020-01-28

WHILE的寫法比CUSOR不耗資源,若使用的變數不多,建議使用

--讀取帶年月的TABLE
IF OBJECT_ID('tempdb..#T') is not null
	DROP TABLE #T

create table #T (sn int identity(1,1),ym varchar(8))
		
insert into #T (ym)
select '202001' 
union select '202002'
union select '202003'

declare @YM as varchar(6)
declare @i as int = 1

while @i <= (select max(sn) from #T)
begin
	set @YM = (select ym from #T where sn=@i)

	exec('SELECT * FROM TAB_'+ @YM +'')
	
	set @i+=1	
end