2013-08-20 90 views
1

我想在CTE使用情況與此代碼:如何在CTE tsql中使用Case Satement?

Declare @DefinitionType Int = 1 
;With Res 
As 
(
    Case @DefinitionType 
     When 1 Then (Select [ActionId], [Title] From Actions) 
     When 2 Then (Select [AreaId], [Title] From Areas) 
     Else (Select [ContractorScopeId], [Title] From ContractorScopes) 
    End 
) 
Select * From Res 

該錯誤是:

消息156,15級,狀態1,5號線
附近有語法錯誤關鍵字 '案例' 。

如何在CTE中使用Case Satement?

回答

2

你不能。

如果列是兼容的數據類型,你可以做

DECLARE @DefinitionType INT = 1; 

WITH Res 
    AS (SELECT [ActionId], 
       [Title] 
     FROM Actions 
     WHERE @DefinitionType = 1 
     UNION ALL 
     SELECT [AreaId], 
       [Title] 
     FROM Areas 
     WHERE @DefinitionType = 2 
     UNION ALL 
     SELECT [ContractorScopeId], 
       [Title] 
     FROM ContractorScopes 
     WHERE @DefinitionType = 3) 
SELECT * 
FROM Res