1

我想用这个代码在 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

该错误是:

消息 156,级别 15,状态 1,第 5 行
关键字“案例”附近的语法不正确。

如何在 CTE 中使用案例陈述?

4

1 回答 1

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 
于 2013-08-20T11:17:29.490 回答