无法将2 varchar与相同值相关联

时间:2012-10-12 15:12:55

标签: sql sql-server-2000

我有这两个表

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ÑEDEDOMEDES,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,
201201887,JOSE ALBERTO,MATOS ,,

和此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 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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)