SQL Server CASE .. WHEN .. IN 语句
Posted
技术标签:
【中文标题】SQL Server CASE .. WHEN .. IN 语句【英文标题】:SQL Server CASE .. WHEN .. IN statement 【发布时间】:2011-08-27 22:02:00 【问题描述】:在 SQL Server 2005 上,我正在尝试查询此选择语句
SELECT AlarmEventTransactionTableTable.TxnID,
CASE AlarmEventTransactions.DeviceID
WHEN DeviceID IN( '7', '10', '62', '58',
'60', '46', '48', '50',
'137', '139', '142', '143', '164' )
THEN '01'
WHEN DeviceID IN( '8', '9', '63', '59',
'61', '47', '49', '51',
'138', '140', '141', '144', '165' )
THEN '02'
ELSE 'NA'
END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM multiMAXTxn.dbo.AlarmEventTransactionTable
它返回下面的错误
消息 156,级别 15,状态 1,第 4 行 关键字“IN”。
请就我的代码可能有什么问题给我一些建议。
【问题讨论】:
【参考方案1】:试试这个...
SELECT
AlarmEventTransactionTableTable.TxnID,
CASE
WHEN DeviceID IN('7', '10', '62', '58', '60',
'46', '48', '50', '137', '139',
'142', '143', '164') THEN '01'
WHEN DeviceID IN('8', '9', '63', '59', '61',
'47', '49', '51', '138', '140',
'141', '144', '165') THEN '02'
ELSE 'NA' END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM
multiMAXTxn.dbo.AlarmEventTransactionTable
只需删除突出显示的字符串
选择 AlarmEventTransactionTableTable.TxnID, 案例 AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)
【讨论】:
我已将它作为 CASE WHEN DeviceID IN('7', '10', '62', '58', '60', '46', '48', '50', ' 137', '139', '141', '145', '164') THEN '01' WHEN DeviceID IN('8', '9', '63', '59', '61','47' , '49', '51', '138', '140','142', '146', '165') THEN '02' ELSE 'NA' END AS clocking,【参考方案2】:CASE AlarmEventTransactions.DeviceID
应该只是 CASE
。
你正在混音the 2 forms of the CASE
expression。
【讨论】:
谢谢,我已将其修复为如下所示【参考方案3】:感谢您的回答 我已将语句修改为如下所示
SELECT
AlarmEventTransactionTable.TxnID,
CASE
WHEN DeviceID IN('7', '10', '62', '58', '60',
'46', '48', '50', '137', '139',
'141', '145', '164') THEN '01'
WHEN DeviceID IN('8', '9', '63', '59', '61',
'47', '49', '51', '138', '140',
'142', '146', '165') THEN '02'
ELSE 'NA' END AS clocking,
AlarmEventTransactionTable.DateTimeOfTxn
FROM
multiMAXTxn.dbo.AlarmEventTransactionTable
【讨论】:
【参考方案4】:使用“简单大小写”以手写方式写出时可能更容易阅读,例如
CASE DeviceID
WHEN '7 ' THEN '01'
WHEN '10 ' THEN '01'
WHEN '62 ' THEN '01'
WHEN '58 ' THEN '01'
WHEN '60 ' THEN '01'
WHEN '46 ' THEN '01'
WHEN '48 ' THEN '01'
WHEN '50 ' THEN '01'
WHEN '137' THEN '01'
WHEN '139' THEN '01'
WHEN '142' THEN '01'
WHEN '143' THEN '01'
WHEN '164' THEN '01'
WHEN '8 ' THEN '02'
WHEN '9 ' THEN '02'
WHEN '63 ' THEN '02'
WHEN '59 ' THEN '02'
WHEN '61 ' THEN '02'
WHEN '47 ' THEN '02'
WHEN '49 ' THEN '02'
WHEN '51 ' THEN '02'
WHEN '138' THEN '02'
WHEN '140' THEN '02'
WHEN '141' THEN '02'
WHEN '144' THEN '02'
WHEN '165' THEN '02'
ELSE 'NA'
END AS clocking
...哪一种让我觉得也许你可以从一个查找表中受益,你可以通过JOIN
完全消除CASE
表达式。
【讨论】:
以上是关于SQL Server CASE .. WHEN .. IN 语句的主要内容,如果未能解决你的问题,请参考以下文章
SQL Server CASE .. WHEN .. IN 语句
[SQL server] IF ELSE 和 CASE WHEN 的用法