T-SQL如何用一列连接一个字符串和一个整数

时间:2017-05-25 18:39:52

标签: tsql

如何用一个字符串和一个整数连接一列? --PEOPLE_ID 000092437,PersonID 92437

select PC.PEOPLE_ID, Idn.PersonId,'Home Row 1', PC.Phone1 from @NextIdentityID Idn INNER JOIN PEOPLECHANGES PC on Idn.People_ID = PC.People_ID --PEOPLE_ID 000092437, PersonID 92437 one is varchar, one is integer
union all select PC.PEOPLE_ID, Idn.PersonId,'Office Row 2', PC.Phone2 from @NextIdentityID Idn INNER JOIN PEOPLECHANGES PC on Idn.People_ID = PC.People_ID
union all select PC.PEOPLE_ID, Idn.PersonId,'Cell Row 3', PC.Phone3 from @NextIdentityID Idn INNER JOIN PEOPLECHANGES PC on Idn.People_ID = PC.People_ID

2 个答案:

答案 0 :(得分:0)

如果将带有前导零的那个转换为整数,则会得到相等的值:

SELECT CONVERT(INT, '000092437') = 92437

但是,这假设您的所有varchar列都可以转换为int。

如果情况并非如此,那么你必须编写一个函数来反向并添加前导零。

答案 1 :(得分:0)

要确保您的varchar()数据不会引发任何错误,您应该检查它是否可以转换为整数。一种方法是使用where子句中的case语句。如果它不可兑换,那么你的连接将无法正常工作 - 但至少你的查询仍可以运行而不会出错。

此示例显示了如何避免潜在错误。

create table #tempa(id int, descr varchar(50));
create table #tempb(id varchar(10), descr varchar(50));

insert into #tempa(id,descr) values (1234,'Body getta body getta');
insert into #tempb(id,descr) values ('001234','sis boom ba - rah rah rah');
insert into #tempa(id,descr) values (5678,'Weagle Weagle War Damn Eagle');
insert into #tempb(id,descr) values ('0005678','Kickem in the butt Big blue');
insert into #tempa(id,descr) values (9012,'this wont have a match');
insert into #tempb(id,descr) values ('x0912','sis boom ba');

Select a.id as a_id, b.id as b_id
,a.descr as a_descr, b.descr as b_descr
from #tempa a
left join #tempb b
on a.id = case when isnumeric(b.id) = 1 then cast(b.id as int) else 0 end

-- this one will raise an error
Select a.id as a_id, b.id as b_id
,a.descr as a_descr, b.descr as b_descr
from #tempa a
left join #tempb b
on a.id = b.id


drop table #tempa;
drop table #tempb;