2012-10-12 41 views
0

我有這2個表可以不涉及2 VARCHAR具有相同值

f_data 
(
id (int, null), 
name(varchar(255), null), 
control (int, null), 
) 

ID名稱控制
1255,阿爾蒙特JIMENEZ ADALGISA,1131238601
92,恩卡納西翁PAMELA,1131237483
3376,FELIZ LUIS MANUEL,1131240995
688,HERRAND海洋DIOMEDES,1131238666
1887年,JOSE ALBERTO馬託斯1131240215

est_data 
(
id(int, null), 
name(varchar(255), null), 
firstname(varchar(255), null), 
lastname(varchar(255), null), 
) 

ID名稱名姓
201201255,ADALGISA,阿爾蒙特,希門尼斯,
201200092,PAMELA,恩卡納西翁,
201223376,LUIS MANUEL,FELIZ,
201200688,DIOMEDES,HERRAND,海洋,
201201887 ,JOSE ALBERTO,馬託斯,

這SQL代碼

select * 
from est_data 
where 
    CASE 
    WHEN 
    lastname = ' ' 
    then 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(name)) 
    ELSE 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(lastname))+' '+ltrim(rtrim(name)) 
    END in 
     (Select ltrim(rtrim(name)) From f_data where id = 1887) 

這樣做的結果是:

CASE 
    WHEN 
    lastname = ' ' 
    then 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(name)) 
    ELSE 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(lastname))+' '+ltrim(rtrim(name)) 
    END 

是 'JOSE ALBERTO MATOS'

並在此結果:

Select ltrim(rtrim(name)) From f_data where id = 1887 

是 'JOSE ALBERTO MATOS'

但是代碼返回0行,當名稱相同時返回事件。這裏可能是什麼問題?

注意:我們正在使用SQL Server 2000

回答

2

仔細查看您的數據。在f_data中,您有「JOSE ALBERTO MATOS」的價值name。在est_data中,您有一個name「JOSE」,一個firstname「ALBERTO」和一個lastname「MATOS」。

現在看看您在est_data上的查詢。您將FIRSTNAME-LASTNAME-NAME合併在一起,在這種情況下,它將是「ALBERTO MATOS JOSE」,它與f_data中的值不匹配。你不是在這兩個地方以相同的方式命名。

如果你不相信我,只要運行這個簡單的腳本來重現問題:

create table #f_data 
(
id int, 
name varchar(255), 
control int 
); 

create table #est_data 
(
id int, 
name varchar(255), 
firstname varchar(255), 
lastname varchar(255) 
); 

insert into #f_data(id, name, control) values (1887, 'JOSE ALBERTO MATOS', 1); 

insert into #est_data(id, name, firstname, lastname) values (1887, 'JOSE', 'ALBERTO', 'MATOS'); 

Select ltrim(rtrim(name)) From #f_data where id = 1887; 

select CASE 
    WHEN 
    lastname = ' ' 
    then 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(name)) 
    ELSE 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(lastname))+' '+ltrim(rtrim(name)) 
    END 
from #est_data; 

select * 
from #est_data 
where 
    CASE 
    WHEN 
    lastname = ' ' 
    then 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(name)) 
    ELSE 
    ltrim(rtrim(firstname)) + ' ' + ltrim(rtrim(lastname))+' '+ltrim(rtrim(name)) 
    END in 
     (Select ltrim(rtrim(name)) From #f_data where id = 1887); 
0

使用子查詢:

select * from (
    select e.*, 
     CASE 
     WHEN e.lastname = ' ' 
     THEN ltrim(rtrim(e.firstname)) + ' ' + ltrim(rtrim(e.name)) 
     ELSE ltrim(rtrim(e.firstname)) + ' '+ltrim(rtrim(e.lastname)) + ' ' + ltrim(rtrim(e.name)) 
     END as wrappedName 
    from est_data e 
) where wrappedName = 
     (select ltrim(rtrim(name))) from f_data where id = 1887)