2011-11-08 89 views
1
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附近有語法錯誤 '='。T-SQL - 錯誤上Case語句

如果你在你的sql server中有Northwind Database,你可以執行這個查詢。

我不明白問題在哪裏。任何人都可以幫我解決這個問題嗎?

回答

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 

您也不能指定這樣的別名。在CASE塊之後使用AS關鍵字。

編輯:根據亞當溫格的評論,你確實可以在你的查詢中寫入別名[alias] = fieldname。感謝您的更正!

+0

鯊魚,我敢肯定,你可以使用'[別名] = CASE語句'別名,儘管我更喜歡'END'後的別名。 –

+0

@AdamWenger我不知道。我必須測試一下!感謝您的糾正,這些小小的不太知名的信息讓我們變得更好!再次感謝。 – 2011-11-09 01:25:22

+0

@AdamWenger果然,你是對的。我修改了我的答案。謝謝! – 2011-11-09 01:27:25

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 
+0

非常感謝你。此代碼工作正常.. – mark

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 
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