简体   繁体   中英

In SQL Server, testing a uniqueidentifier for null doesn't seem to work

Not sure if this is the best approach, but I have a stored procedure with an OUTPUT parameter as follows;

create procedure [dbo].[sp_get_site_idx]
@site_name varchar(100),
@result uniqueidentifier output
as
begin
  select @result = [primary_idx_col] from [site] where upper([site].[site_name]) = upper(@site_name);
  if (@result is null)
  begin
    < insert a new row>
    < run the above select statement again>
  end;
end;

When a @site_name that I know does not exist is supplied, the condition (@result is null) is never true, in fact @result appears to be undefined (similar to when there's an exception in a programming language).

Table [site] was created as:

create table [site] (
[primary_idx_col] UNIQUEIDENTIFIER DEFAULT NEWID() constraint pk_site_pk primary key,
...
);

Strangely, if I slightly modify the select statement to:

select @result = [primary_idx_col] from [site] where upper([site].[site_name]) = upper(@site_name) group by [primary_idx_col];

then (@result is null) will evaluate to true.

Please could you explain this behaviour? What is worng with the first select statement? Thanks in advance.

UNIQUEIDENTIFIER can be checked against NULL.

I tried putting your code into a test database, and the logic seems to be working for me.

If I call your Stored Procedure with:

DECLARE @RESULT2 UNIQUEIDENTIFIER;
EXEC dbo.SP_GET_SITE_IDX @SITE_NAME = '<INSERT VALUE HERE>', -- varchar(100)
    @RESULT = @RESULT2 OUTPUT;-- uniqueidentifier
SELECT @RESULT2

then I get the proper result depending on whether the site name is in the table or not.

Does it not insert the row in your IF, in the procedure?

Are you sure the site in question is not in your table?

It is possible that the site is in your table, but with a NULL key/value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM