3

Sqlserver中0和空字符串相等的问题

 2 years ago
source link: https://www.mihu.live/archives/299/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Sqlserver中0和空字符串相等的问题

yan
2021-08-17 / 0 评论 / 41 阅读 / 已收录
08/17

今天在SQL server中写存储过程时遇到一种0和空字符串相等的问题。
场景:表A有value1(varchar)和value2(int)两个字段,现在插入一条新的数据(v1,v2),如果v1已存在,则给value2加上v2,若v1不存在则插入新的(v1,v2)
(这个逻辑用merge into会更好些)
开始我是这么写的

declare @flag=int
select @flag=value2 from A where A.value1=v1
if(@flag='')
  insert into ...
else 
  update A...

但是这样是有问题的,当查询不到这条数据时,确实会插入,但是当value2=0的时候,这么写它依然会执行insert,也就是0='',可以通过下面的存储过程验证一下:

CREATE PROCEDURE TEST
AS 
BEGIN 
    declare @a int
    declare @b varchar
    set @a=0
    set @b=0
    if(@a='')
        print('int a')
    if(@b='')
        print('varchar b')
END
GO

然后执行会发现输出为 int a ,原因在于varchar和int是存在隐式转换的,导致转换之后0和空字符串变成了相等的。

参考:https://www.cnblogs.com/liubaolongcool/archive/2011/08/24/2152552.html


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK