如何将case语句的结果用于另一个操作?

时间:2017-03-01 15:12:58

标签: sql-server-2008

select 'Test '+m.testname+' '+         
    Case
        When m.value = 'ttttt' Then 'tt'
        When m.styleName = 'ppppp' Then 'pp'
        When m.styleName = 'qqqqq' Then 'qq'
        When m.styleName = 'yyyyyy' Then 'yy'           
        Else ''
    End     from testtable m   where m.id=10'

这是我的查询,我需要检查case语句后形成的字符串的长度。如果长度大于35,那么我想从“m.testname”字段中删除字符。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

您可以将当前查询用作派生表:

select  YourString, 
        LEN(YourString) [Length],
        Case 
            When LEN(YourString) > 35 THEN REPLACE(YourString,testname,'')
            Else YourString
        End YourNewString
from (  select 'Test '+m.testname+' '+         
            Case
                When m.value = 'ttttt' Then 'tt'
                When m.styleName = 'ppppp' Then 'pp'
                When m.styleName = 'qqqqq' Then 'qq'
                When m.styleName = 'yyyyyy' Then 'yy'           
                Else ''
            End YourString,
            m.testname
        from testtable m   
        where m.id=10) a
;

或者您可以使用CTE:

WITH CTE AS
(
    select 'Test '+m.testname+' '+         
        Case
            When m.value = 'ttttt' Then 'tt'
            When m.styleName = 'ppppp' Then 'pp'
            When m.styleName = 'qqqqq' Then 'qq'
            When m.styleName = 'yyyyyy' Then 'yy'           
            Else ''
        End YourString,
        m.testname
    from testtable m   
    where m.id=10
)
select  YourString, 
        LEN(YourString) [Length],
        Case 
            When LEN(YourString) > 35 THEN REPLACE(YourString,testname,'')
            Else YourString
        End YourNewString
from CTE;