如何在条件时循环一个案例

时间:2016-09-16 10:47:12

标签: sql sql-server loops case-when

我的列名为col1,col2,col12,我有exm1,exm2到exm12。

我该怎么做?

declare @i= 1

do until i=12
(

case 
when col@i <= 25000 then '1. xxxx <= 25K         '

when col@i > 25000 and col@i <=100000  then '2. 25K < xxxx <= 100K '

when col@i > 100000 then '6. xxxx >= 100K    '

else end as column_group_@1

set i=i+1

)

与exm1相同

1 个答案:

答案 0 :(得分:0)

IF OBJECT_ID('tempdb..#temp1') IS NOT NULL DROP TABLE #temp1
GO
create table #Temp1(col@i 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 column_group_@1
    from YourTableName'
    Insert Into #Temp2 values(@qrystr)
set @i=@i+1

end
Select * From #Temp2