简体   繁体   English

在SQL Server中,测试为null的uniqueidentifier似乎不起作用

[英]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; 不知道这是否是最好的方法,但是我有一个带有OUTPUT参数的存储过程,如下所示;

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). 当提供我不知道的@site_name ,条件(@result is null)永远不会为真,实际上@result似乎是未定义的(类似于编程语言中存在异常的情况)。

Table [site] was created as: [site]创建为:

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语句稍微修改为:

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. 然后(@result is null)将评估为true。

Please could you explain this behaviour? 请您能解释一下这种行为吗? What is worng with the first select statement? 第一条select语句会带来什么? Thanks in advance. 提前致谢。

UNIQUEIDENTIFIER can be checked against NULL. 可以将UNIQUEIDENTIFIER对照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? 是否不会在该过程中将行插入您的IF中?

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? 该站点可能在您的表中,但键/值为NULL?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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