TSQL正在比较2个uniqueidentifier值,但未按预期工作



我正在尝试比较2个uniqueidentifier值,如下查询所示。但是,如果一个值为null,而另一个值不为null,则结果为"相同"?!我确信这两个值都是uniqueidentifier,并且还尝试将两个值强制转换为uniqueidentification以确保绝对正确。正在比较的2个值来自具有不同排序规则的不同数据库。排序规则有什么不同吗?任何想法都将不胜感激。

select [result] = case when 
    [target].StaffID <> [source].StaffID then 'different' 
    else 'same' 
    end
from
    ...

如果我更换<>如果为=,则查询会认为2个null值不匹配。

编辑:

我用过:

declare @empty uniqueidentifier
set @empty = '00000000-0000-0000-0000-000000000000'
... isnull(somevalue, @emtpy) <> isnull(othervalue, @empty) ...

NULL既不等于有也不等于无。通常,您会通过与IS NULL进行比较来检查空值。例如,

somefield IS NULL

您可以考虑使用COALESCE来做您要做的事情——只需确保使用相同的数据类型(在本例中为UniqueIdentifier):

...
  case 
    when coalesce(t.StaffID,'00000000-0000-0000-0000-000000000000') <> 
         coalesce(t2.StaffID,'00000000-0000-0000-0000-000000000000')
    then 'different' 
    else 'same' 
  end
...

http://sqlfiddle.com/#!3/181e9d/1

null更多的是未知的,它实际上不是一个值。不幸的是,SQL会告诉您null=null是false。

基本上,您必须将null强制转换为空字符串,才能进行比较。我们使用IFNULL(值,替换)来实现这一点。。。

http://msdn.microsoft.com/en-us/library/ms184325.aspx

希望这能有所帮助。

select case when null = null then 'equal' else 'not equal' end

以上将是"不相等"

select case when ISNULL(null, '') = ISNULL(null, '') then 'equal' else 'not equal' end

这将是"相等"的

最后你的案子。。。

select [result] = case when 
    ISNULL([target].StaffID, '') <> ISNULL([source].StaffID, '') then 'different' 
    else 'same' 
    end
from

相关内容

最新更新