如果值返回值。如果记录不存在或列为null,则在Sql Server中以不同的方式返回0

时间:2015-07-09 13:22:33

标签: sql sql-server null

如果没有记录或0为空,我想返回Column1

select @var =  Column1
from myschema.mytable
where Id = @suppliedId;

select isnull(@var, 0);

如果0为空,则上述代码会输出Column1。或者如果找不到行

虽然我试图保存一些按键,但结果却是,

select isnull(Column1, 0)
from myschema.mytable 
where Id = @suppliedId;

如果null为空或没有行,则上述代码输出Column1

这里有什么问题吗?或者有没有更短的方式来编写第一个代码?

2 个答案:

答案 0 :(得分:4)

You can do

SELECT @var = ISNULL(MAX(Column1), 0)
FROM   myschema.mytable
WHERE  Id = @suppliedId; 

A scalar aggregate always returns a single row even if the underlying query returns zero rows.

答案 1 :(得分:1)

没有真正保存击键,但这样的事情可能会有所帮助: - )

SELECT TOP 1 tbl.field
FROM
(
    SELECT 0 AS inx, 'no record' AS field
    --if only one row is possible, than set '1' literally
    UNION SELECT ROW_NUMBER() OVER(ORDER BY mytable.orderfield), ISNULL(mytable.Land,'is null')
    FROM mytable
    WHERE IDENTITY = @suppliedID
    ) AS tbl
ORDER BY tbl.inx DESC