背景:有一张表叫t_Flow,里面有两个字段 c_MaxNum int , c_Id intselect top 1 c_MaxNum from t_Flow where c_Id=-1
--返回空的结果集declare @Num int
set @Num=2
set @Num=(select top 1 c_MaxNum from t_Flow where c_Id=-1)
set @Num=@Num+1
print @Num
--输出:空declare @Num1 int
set @Num1=2
select top 1  @Num1=c_MaxNum from t_Flow where c_Id=-1
set @Num1=@Num1+1
print @Num1
--输出: 2疑问:为什么两者输出的不一样

解决方案 »

  1.   

    declare @Num int
    set @Num=2
    set @Num=(select top 1 c_MaxNum from t_Flow where c_Id=-1)--把空值赋给@Num
    set @Num=@Num+1--空值加1认为null
    print @Num--------------------------declare @Num1 int
    set @Num1=2
    select top 1 @Num1=c_MaxNum from t_Flow where c_Id=-1--这个并不是在给@Num1赋值,查询结果为空,@Num1的值不变
    set @Num1=@Num1+1
    print @Num1
    --输出: 2
      

  2.   

    第二个,如果后面的查询能得到值,则@Num会被赋值
      

  3.   

    set 和 select的区别:
    set是对其赋值,select选择值,如果select的值为空,变量的原值不变.
      

  4.   

    declare @num int=2
    select top 1 @Num1=c_MaxNum from t_Flow where c_Id=-1
    print @num
    --如果 SELECT 语句没有返回行,变量将保留当前值
    select @Num1=(select top 1 c_MaxNum from t_Flow where c_Id=-1)
    print @num
    --如果 expression 是不返回值的标量子查询,则将变量设为 NULL
    第一个结果为2,第二个为空