2017-03-01 57 views
1
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 statement.if長度大於35然後我想從「m.testname」字段中刪除字符串形成的字符串的長度。 感謝您的幫助。如何使用case語句的結果來進行其他操作?

回答

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; 
+0

thanksss其工作 – isree