T-SQL - 案例陈述错误

时间:2011-11-08 14:00:50

标签: sql-server tsql sql-server-2005-express

USE NORTHWIND;
GO
SELECT SHIPCOUNTRY,[ORDERS_ID] = 
CASE ORDERID
WHEN ORDERID = 10300
THEN 'I AM FROM 10300'
WHEN ORDERID = 10400
THEN 'I AM FROM 10400'
WHEN ORDERID = 10500
THEN 'I AM FROM 10500'
ELSE 'I AM OUT OF RANGE'
END
FROM ORDERS;
GO
  

错误 - 消息102,级别15,状态1,行3'='附近的语法不正确。

如果您的sql server中有northwind数据库,则可以执行此查询。

我不明白问题出在哪里。任何人都可以帮我解决这个问题吗?

5 个答案:

答案 0 :(得分:5)

试试这个:

USE NORTHWIND; 
GO 
SELECT SHIPCOUNTRY,  
CASE ORDERID 
WHEN 10300 
THEN 'I AM FROM 10300' 
WHEN 10400 
THEN 'I AM FROM 10400' 
WHEN 10500 
THEN 'I AM FROM 10500' 
ELSE 'I AM OUT OF RANGE' 
END as OrdersId
FROM ORDERS; 
GO 

如果您在初始CASE xxxx语句中明确说明,则无法在WHEN子句中重复该变量。这也同样有效:

USE NORTHWIND; 
GO 
SELECT SHIPCOUNTRY, 
CASE
WHEN ORDERID = 10300 
THEN 'I AM FROM 10300' 
WHEN ORDERID = 10400 
THEN 'I AM FROM 10400' 
WHEN ORDERID = 10500 
THEN 'I AM FROM 10500' 
ELSE 'I AM OUT OF RANGE' 
END as OrdersId
FROM ORDERS; 
GO 

您也无法分配这样的别名。在AS阻止后使用CASE关键字。

编辑:根据Adam Wenger的评论,您确实可以在查询中编写[alias] = fieldname之类的别名。谢谢你的纠正!

答案 1 :(得分:3)

USE NORTHWIND;
GO
SELECT SHIPCOUNTRY,
CASE ORDERID
WHEN  10300
THEN 'I AM FROM 10300'
WHEN  10400
THEN 'I AM FROM 10400'
WHEN  10500
THEN 'I AM FROM 10500'
ELSE 'I AM OUT OF RANGE'
END as [ORDERS_ID]
FROM ORDERS;
GO

答案 2 :(得分:3)

case构造可以有两种不同的形式:

case n
  when n then n
  when n then n
end

case
  when n = n then n
  when n = n then n
end

你正在混合它们。使用:

SELECT SHIPCOUNTRY,[ORDERS_ID] = 
  CASE ORDERID
    WHEN 10300 THEN 'I AM FROM 10300'
    WHEN 10400 THEN 'I AM FROM 10400'
    WHEN 10500 THEN 'I AM FROM 10500'
    ELSE 'I AM OUT OF RANGE'
  END
FROM ORDERS

答案 3 :(得分:2)

CASE有两种格式:简单和搜索。你正在混合它们。

http://msdn.microsoft.com/en-us/library/ms181765.aspx

答案 4 :(得分:1)

USE NORTHWIND;
GO
SELECT SHIPCOUNTRY,
CASE ORDERID 
  WHEN 10300
    THEN 'I AM FROM 10300'
  WHEN 10400
    THEN 'I AM FROM 10400'
  WHEN 10500
    THEN 'I AM FROM 10500'
  ELSE 'I AM OUT OF RANGE'
END ORDERS_ID
FROM ORDERS;
GO