我想在cte中使用这个代码的用例:
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
该错误是:
Msg 156,Level 15,State 1,Line 5
关键字“Case”附近的语法不正确。
如何在CTE中使用Case satement?
答案 0 :(得分: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