Sql server 如何从记录中获取列的最大值?如果在SELECT中没有匹配的记录,如何获取0?

Sql server 如何从记录中获取列的最大值?如果在SELECT中没有匹配的记录,如何获取0?,sql-server,Sql Server,我有一个用于插入的存储过程。当我 我正在插入一条记录,我想要释放的值 大于等于最高值的一个。所以这里 这是我的代码: DECLARE @MaxRelease int; SELECT @MaxRelease = max(Release) FROM dbo.Test WHERE TestTypeId = @TestTypeId AND ExamId = @ExamId AND Title = @Title;

我有一个用于插入的存储过程。当我 我正在插入一条记录,我想要释放的值 大于等于最高值的一个。所以这里 这是我的代码:

    DECLARE @MaxRelease int;

    SELECT @MaxRelease = max(Release)
    FROM   dbo.Test
    WHERE  TestTypeId = @TestTypeId
    AND    ExamId     = @ExamId
    AND    Title      = @Title;

    INSERT ... @MaxRelease + 1 ... etc.
但是,我如何才能做到这样,如果SELECT没有返回任何内容(因为
没有当前记录)说明@MaxRelease的值将为0?

将@MaxRelease的初始值指定为零

DECLARE @MaxRelease int = 0;

SELECT @MaxRelease = max(Release)
FROM   dbo.Test
WHERE  TestTypeId = @TestTypeId
AND    ExamId     = @ExamId
AND    Title      = @Title
GROUP BY TestTypeId;
如果select没有返回任何内容,则@MaxRelease将不会被修改。

尝试此操作

DECLARE @MaxRelease int;

SELECT @MaxRelease = max(Release)
FROM   dbo.Test
WHERE  TestTypeId = @TestTypeId
AND    ExamId     = @ExamId
AND    Title      = @Title;

INSERT ... CASE WHEN @MaxRelease IS NULL THEN 0 ELSE @MaxRelease + 1 END ... etc.
可以使用替换值替换空值

SELECT @MaxRelease = isnull(max(Release), 0)
FROM   dbo.Test
尝试使用或

SELECT @MaxRelease = isnull(max(Release),0)
FROM   dbo.Test
WHERE  TestTypeId = @TestTypeId
AND    ExamId     = @ExamId
AND    Title      = @Title;
if @MaxRelease is null
begin
set @MaxRelease =0
end

Then Execute Insert Query here.