SQL - ISNULL然后比较字符串值

时间:2014-03-09 18:23:46

标签: sql sql-server tsql

create table aaa (ID nvarchar(80), Is_enduser varchar(5), identityy int)
create table bbb (ID varchar(90), Is_enduser bit, identityy int)
insert into aaa values (null, 'False',1),(null, 'False',2), (null, 'True',3)
insert into bbb values ('*N/A', 0,1),('*N/A', 0,2),('*N/A', 1,3)

所以我有两个具有不同值的表,但它们实际上具有相同的含义,null = * N / A. 'True'= 1,'False'= 0

所以我想比较这两个表中的数据

我这样做的方法是使用Cursor逐行比较,我第一次使用表'aaa'作为基表

declare c cursor for 
select  isnull(ID,'*N/A'), 
    case is_enduser when 'False' then '0' when 'True' then '1' end,
    identityy
    from aaa
open c
    declare @ID nvarchar(80), @is_enduser varchar(5), @identityy int
    fetch next from c into @ID, @is_enduser, @identityy
    while @@FETCH_STATUS = 0
        begin
            begin
            if exists (select ID,  convert(varchar(5), is_enduser, identityy)  from bbb
            where ID = @ID and Is_enduser = @is_enduser and identityy = @identityy)
                Print 'Find Match'
            else 
                print 'no match'
            End
        fetch next from c into @id, @is_enduser, @identityy
        end
close c
deallocate c

当我想用'bbb'作为我的基表进行比较时,我无法得到我想要的结果

declare b cursor for
select  ID , is_enduser, identityy from bbb
open b
declare @ID varchar(20), @is_enduser varchar(20), @identityy int
fetch next from b into @ID, @is_enduser, @identityy
while @@FETCH_STATUS = 0
    Begin
        Begin
        IF EXISTS ( select ISNULL(ID, '*N/A'), 
        case is_enduser when 'False' then '0' when 'True' then '1' end identityy from aaa
        where ID = @ID and is_enduser = @is_enduser and identityy = @identityy)
            print 'find match'
        else 
            print 'no match'
        End
        fetch next from b into @ID, @is_enduser, @identityy
    End
close b
deallocate b

所以我的第二个光标找不到匹配,我试图打印两个字符串的值,它们实际上是相同但是它们不匹配 请帮忙,谢谢

UPDATED - SOLUTION - 在第二个游标中,将语句更改为

IF EXISTS ( select ID, Is_enduser, identityy from aaa
where ISNULL(ID,'*N/A') = @ID 
and case is_enduser when 'False' then '0' when 'True' then '1' end = @is_enduser
and identityy = @identityy)

1 个答案:

答案 0 :(得分:2)

将第二个光标中的ID = @ID更改为ISNULL(ID,@ID) = @ID