当我执行我的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'
我收到以下错误:
子查询返回的值超过1。这是不允许的 子查询跟随=,!=,<,< =,>,> =或当子查询用作 表达。
答案 0 :(得分:5)
如何使用COALESCE()
?
SELECT COALESCE(model_id, part_id)
FROM request_unit
WHERE request_id = '4357';
不需要IF
。
错误本身似乎很明显。 request_unit
中有多行,request_id
为4357。
答案 1 :(得分:1)
试试这个......
这意味着model_id
request_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'
答案 2 :(得分: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的答案是首选的
答案 3 :(得分:0)
除了@ GordonLinoff的回答,您还可以编写以下内容以获取列名称:
SELECT COALESCE(model_id, part_id) as 'YOURCOLUMNNAME'
FROM request_unit
WHERE request_id = '4357';
答案 4 :(得分:0)
你可以这样做;
SELECT COALESCE(model_id, part_id) FROM request_unit WHERE request_id = '4357'
SELECT ISNULL(model_id, part_id) FROM request_unit WHERE request_id = '4357'
SELECT CASE WHEN model_id IS NULL THEN part_id ELSE model_id END FROM request_unit WHERE request_id = '4357'
IIF Starting 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'