2013-08-20 50 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