What does the select statement return if the condition does not match?

For example, if I have the following statement:

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

In this case, if the selection does not return any results, what will be the value @uid?

+3
source share
3 answers

in simple words it will be null

I tried a simple temporary table to verify this

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

 insert into @temp select 'z'

declared a variable nvarchar typeand got a value in this case, when the condition is not met, then there is zero, and if you see the print statement, then nothing will be printed

declare @test nvarchar(50)


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

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


 print @test

I just insert this again to confirm that zero exists

+2
source

It will return NULL in this case

+2

, :

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

, , null

 If @uid IS NULL
      set @uid = 0
+1
source

Source: https://habr.com/ru/post/1606895/


All Articles