如果条件不匹配,select语句会返回什么?

时间:2012-11-08 09:59:32

标签: sql sql-server select

例如,如果我有以下声明:

declare @uid int;
set @uid = (select id from tablename where condition)

在这种情况下,如果select没有返回结果,@uid的值是什么?

3 个答案:

答案 0 :(得分:2)

在这种情况下会返回NULL

答案 1 :(得分:2)

简单来说就是null

我已经制作了简单的临时表来测试这个

declare @temp table 
 (
   id int identity(1,1) not null  ,
   alpha nvarchar(50)
 )

 insert into @temp select 'z'

声明了一个变量nvarchar type并且在这个条件不满足的情况下得到值然后有空,如果你看到print语句那么应该没有什么可以打印

declare @test nvarchar(50)


 select @test=alpha from @temp where id=70

 insert into @temp  select @test 
 select * from @temp


 print @test

我只是再次插入此内容以确认存在空

答案 2 :(得分:1)

做一个检查,如下:

declare @uid int;
set @uid = (select id from tablename where condition)
If @uid IS NULL
  print 'uid is null or not exist'

OR,您可以设置默认值,以防它返回null

 If @uid IS NULL
      set @uid = 0