たとえば、次のステートメントがあるとします。
declare @uid int;
set @uid = (select id from tablename where condition)
この場合、select が結果を返さない場合、 の値は何に@uid
なるでしょうか?
たとえば、次のステートメントがあるとします。
declare @uid int;
set @uid = (select id from tablename where condition)
この場合、select が結果を返さない場合、 の値は何に@uid
なるでしょうか?
簡単に言えば、それはnullになります
これをテストするための簡単な一時テーブルを作成しました
declare @temp table
(
id int identity(1,1) not null ,
alpha nvarchar(50)
)
insert into @temp select 'z'
変数を宣言し、nvarchar type
条件が満たされない場合はnullがあり、printステートメントで確認すると、何も出力されないはずです。
declare @test nvarchar(50)
select @test=alpha from @temp where id=70
insert into @temp select @test
select * from @temp
print @test
これをもう一度挿入して、nullがあることを確認します
その場合はNULLを返します
次のようにチェックを行います。
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