将CAS大小写转换为IF ELSE,因为CASE ELSE未执行

时间:2014-10-15 01:48:04

标签: sql sql-server sql-server-2008 if-statement case

我有以下

之类的SQL语句
    declare @mydata nvarchar(MAX) = '';
    select @mydata = @mydata + case IsOwner when 1 then

    ----some sql statement like

                      '(select top 1 mytable.Value from ['+@TableVariableName+'] as mytable where 
['+ ColumnNames + ']=mytable.Key) as ['+ColumnNames+'],' 


    else case IsActive when 1 then 

    ----some sql statement 

    else
    ----some sql statement
    END END

Every time last else statement should executecase is not IsOwner or IsActive 但是I'm unable to else every timemay be because of case scope don't know

  

我需要将上述语句转换为IF ELSE

我试过跟随

     declare @mydata nvarchar(MAX) = '';
        select @mydata = @mydata + 
        IF(IsOwner = 1) 
    BEGIN

        ----some sql statement like 
            '(select top 1 mytable.Value from ['+@TableVariableName+'] as mytable where 
['+ ColumnNames + ']=mytable.Key) as ['+ColumnNames+'],' 

        END
        else if ( IsActive = 1)
    BEGIN 

        ----some sql statement 
        END
        else
    BEGIN
        ----some sql statement
    END

我收到语法错误:(

  

我只想确保没有条件被执行,它应该每次都调用最后一次

1 个答案:

答案 0 :(得分:1)

根据您的示例代码,这是我的测试代码,它返回来自最后一个的02

declare @mydata nvarchar(MAX) = ''
declare @IsOwner int = 2
declare @IsActive int = 2
select @mydata = @mydata + case @IsOwner when 1 then

'11'

else case @IsActive when 1 then 

 '21'

else  '02' end
end

select @mydata

所以我认为问题不是case语句,可能与源表中IsOwner和IsActive的值有关。