【问题标题】:How can I use Case satement in CTE tsql?如何在 CTE sql 中使用 Case 语句?
【发布时间】:2013-08-20 19:29:06
【问题描述】:

我想用这个代码在 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 行
关键字“Case”附近的语法不正确。

如何在 CTE 中使用案例分句?

【问题讨论】:

    标签: sql-server tsql common-table-expression


    【解决方案1】:

    你不能。

    如果列是兼容的数据类型,您可以这样做

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多