带有Transact SQL的IF语句

时间:2016-07-28 11:05:20

标签: sql sql-server-2008 tsql

当我执行我的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。这是不允许的   子查询跟随=,!=,<,< =,>,> =或当子查询用作   表达。

5 个答案:

答案 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)

你可以这样做;

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'

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'