2017-05-25 34 views
0

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

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 
+0

https://docs.microsoft.com/en-us/sql/t-sql/functions/conversion-functions-transact-sql除了 – user6144226

+0

:性能可能会因您选择哪个方向上有很大的不同将'VarChar'转换为'Int',反之亦然。这取决于是否有索引,索引统计,......。可能值得添加索引计算列以提高性能。提示:使用合适的软件(MySQL,Oracle,DB2,...)和版本(例如, '的SQL服务器2014'。语法和功能的差异往往会影响答案。我已经假设最近的一些年份的SQL Server。 – HABO

回答

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 ('0','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; 
0

如果转换为整数的一个前导零,你会得到相等值:

SELECT CONVERT(INT, '000092437') = 92437 

然而,这种假设所有的VARCHAR列的可被转换为int。

如果不是这种情况,那么你必须编写一个功能去另一种方式并添加前导零。

相关问题