2016-09-16 55 views
1

時,如何循環一個案例我有名爲col1,col2的列到col12,我有exm1,exm2到exm12。當條件爲

我該怎麼做?

declare @i= 1 

do until i=12 
(

case 
when [email protected] <= 25000 then '1. xxxx <= 25K   ' 

when [email protected] > 25000 and [email protected] <=100000 then '2. 25K < xxxx <= 100K ' 

when [email protected] > 100000 then '6. xxxx >= 100K ' 

else end as [email protected] 

set i=i+1 

) 

同樣與EXM1

+0

哪個DBMS您正在使用?SQL服務器? –

+0

是的SQL Server。 –

回答

0
IF OBJECT_ID('tempdb..#temp1') IS NOT NULL DROP TABLE #temp1 
GO 
create table #Temp1([email protected] int) 
IF OBJECT_ID('tempdb..#temp2') IS NOT NULL DROP TABLE #temp2 
GO 
create table #Temp2(qrystr varchar(max)) 

declare @i int 
declare @strcon varchar(5) 
declare @qrystr varchar(max) 
set @i= 1 
while(@i<12) 
begin 
    set @strcon=rtrim(ltrim(str(@i))) 
    set @qrystr=' 
    select 
     ( 
      case 
      when col' + @strcon + '<= 25000 then ''1. xxxx <= 25K  '' 
      when ' + @strcon +'> 25000 and ' + @strcon +' <=100000 then ''2. 25K < xxxx <= 100K '' 
      when '+ @strcon +'> 100000 then ''6. xxxx >= 100K '' 
      end 
     )as [email protected] 
    from YourTableName' 
    Insert Into #Temp2 values(@qrystr) 
set @[email protected]+1 

end 
Select * From #Temp2 
+0

謝謝Poonam。但是列名就像col1,我想把「1」作爲這樣的變量:col @ i where @ i = 1所以我想循環從col1到col12的條件,列結果也會處理@i condtion column_group_ @我。 –