2016-07-28 165 views
1

當我執行我的Transact SQL代碼IF使用Transact SQL語句

IF (SELECT model_id FROM request_unit where request_id = '4357') IS NULL 
    SELECT part_id FROM request_unit WHERE request_id = '4357' 
ELSE 
    SELECT model_id FROM request_unit where request_id = '4357' 

我收到以下錯誤:

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

回答

5

如何只使用COALESCE()

SELECT COALESCE(model_id, part_id) 
FROM request_unit 
WHERE request_id = '4357'; 

IF是不需要的。

錯誤本身似乎很明顯。有一個在request_unit多行,其中request_id是4357.

+0

它很好用,謝謝,但結果表的標題沒有顯示列的名稱(model_id或part_id)。它顯示'沒有列名' – Ces1919

+1

@NaderLaroussi只是別名,就像(model_id ModelID,part_id PartID) –

1

嘗試......

這意味着有幾個model_idrequest_id = '4357'

IF Not Exists (SELECT model_id FROM request_unit where request_id = '4357') 
    SELECT part_id FROM request_unit WHERE request_id = '4357' 
ELSE 
    SELECT model_id FROM request_unit where request_id = '4357' 
0
IF (SELECT top 1 model_id FROM request_unit where request_id = '4357') IS NULL 
    SELECT part_id FROM request_unit WHERE request_id = '4357' 
ELSE 
    SELECT model_id FROM request_unit where request_id = '4357' 

這也能成爲使用,但@Gordon Lioff的回答是首選

0

隨着@ GordonLinoff的答案你可以請寫下列內容以獲得列名:

SELECT COALESCE(model_id, part_id) as 'YOURCOLUMNNAME' 
FROM request_unit 
WHERE request_id = '4357'; 
0

您可以這樣做;

COALESCE

SELECT COALESCE(model_id, part_id) FROM request_unit WHERE request_id = '4357' 

ISNULL

SELECT ISNULL(model_id, part_id) FROM request_unit WHERE request_id = '4357' 

CASE WHEN

SELECT CASE WHEN model_id IS NULL THEN part_id ELSE model_id END FROM request_unit WHERE request_id = '4357' 

IIFStarting with 2012

SELECT IIF(model_id IS NULL, part_id, model_id) THEN part_id ELSE model_id END FROM request_unit WHERE request_id = '4357'