0

我有这两张桌子

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

ID名称控制
1255,ALMONTE JIMENEZ ADALGISA,1131238601
92,ENCARNACION PAMELA,1131237483
3376,Feliz Luis Manuel,1131240995
688,HerrandMariñeDioMedes,1131238666
1887,Jose Alberto Matos,1131240215

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

id name firstname lastname
201201255 ,ADALGISA ,ALMONTE ,JIMENEZ ,
201200092 ,PAMELA ,ENCARNACION ,,
201223376 ,LUIS MANUEL ,FELIZ ,,
201200688 ,DIOMEDES ,HERRAND ,MARIÑE,
20120188

和这个 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

是“何塞·阿尔伯托·马托斯”

结果:

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

是“何塞·阿尔伯托·马托斯”

但是代码返回0行,名称相同时的事件。这里可能有什么问题?

注意:我们使用的是 SQL Server 2000

4

2 回答 2

2

非常仔细地查看您的数据。在f_data你有一个name“JOSE ALBERTO MATOS”的价值。在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);
于 2012-10-12T15:47:47.150 回答
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)
于 2012-10-12T15:56:28.520 回答