【问题标题】:Calling a function in a case statement within select statement is that possible(simply can I have a while loop within case statement)在 select 语句中的 case 语句中调用函数是可能的(我可以在 case 语句中有一个 while 循环)
【发布时间】:2015-10-14 13:01:00
【问题描述】:

我想根据下面的例子选择数据

    select Id, name, address,
    case when department = CIS then @date1 as Date
         else @date2 as Date

@date1@date2 应该从函数中获取。我该怎么做? @date1 应该是 while 循环的输出。请帮我用一个例子解决它

【问题讨论】:

  • select Id, name, address, case when department = CIS then @date1 else @date2 END AS DATTE

标签: sql sql-server select case sql-server-2014-express


【解决方案1】:

您只能有一个列别名,它位于整个表达式之后。此外,请注意您缺少 end 关键字:

SELECT id, 
       name,
       address,
       CASE WHEN department = 'CIS' THEN @date1 ELSE @date2 END AS [date]

编辑:
另请注意,对于简单的相等性检查,您可以使用更简单的语法:

SELECT id, 
       name,
       address,
       CASE department WHEN 'CIS' THEN @date1 ELSE @date2 END AS [date]

【讨论】:

  • SQL 服务器使用[date] 而不是`date`。后者是 MySQL 语法 ;-)
  • @RobIII 是的,是的。没注意,谢谢已编辑和修复。
  • @Mureinik 我的问题是如何调用函数来获取 date1 和 date2 我想做的是通过一个 while 循环我应该在那里找到值.. 这可能吗?
【解决方案2】:

您的案例陈述中忘记了end

这应该可行:

select Id, name, address,
    case when 
         department = CIS then @date1 
         else @date2  
     end as "Date"

【讨论】:

  • This should work 不,因为你(仍然)在第一种情况下有别名;它应该遵循这种情况(你有一个别名);)
猜你喜欢
  • 2011-02-24
  • 2017-01-16
  • 2023-04-07
  • 1970-01-01
  • 2014-12-05
  • 2018-07-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
相关资源
最近更新 更多