如何在sql server中为int类型指定NULL类型

时间:2014-05-16 04:59:19

标签: sql sql-server sql-server-2008

按照我的代码

begin
    declare @Iorder int 
    set @Iorder=0
    declare @no int
    set @no=(select MAX(IOrder) from Team)
    if @no=NULL
        set @Iorder=1
    else
        begin 
            set @Iorder=(select MAX(IOrder) from Team)
            set @Iorder=@Iorder+1
        end 
end

如果在Team表中没有行select MAX(IOrder) from Team语句返回NULL值,那么语句if @no=NULL不正确,因为@noint类型然后SQL Server返回错误Null value is eliminated by an aggregate or other SET operation. 那么如何解决呢?

3 个答案:

答案 0 :(得分:0)

使用is null进行测试。

begin
    declare @Iorder int 
    set @Iorder=0
    declare @no int
    set @no=(select MAX(IOrder) from Team)
    if @no is null
        set @Iorder=1
    else
        begin 
            set @Iorder=(select MAX(IOrder) from Team)
            set @Iorder=@Iorder+1
        end 
end

您的代码可以改为使用isnull()重写。

declare @Iorder int 
select @Iorder = 1 + isnull(max(IOrder), 0) from Team

答案 1 :(得分:0)

你可以简单地完成这一切。

试试这个:

begin
    declare @Iorder int 
    SELECT @Iorder = ISNULL(MAX(IOrder),0)+1 FROM Team
end

<强>解释

如果@Iorder为NULL,

MAX(IOrder)将为1(即0 + 1)。

否则,@Iorder将为MAX(IOrder)+1

答案 2 :(得分:0)

使用SELECT ISNULL(MAX(IOrder),0) FROM Team(如果为null则返回0)并删除if else以检查空值,SELECT ISNULL(MAX(IOrder),0) + 1 FROM Team以防您想要增加值