SQL 连接 Int 列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7096235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenating Int columns
提问by Peter
I have a table called Field_Data and the data in the table looks like:
我有一个名为 Field_Data 的表,表中的数据如下所示:
Date Track_ID Item#
2011-02-25 00:00:00.000 70212 1
2011-02-25 00:00:00.000 70212 2
2011-03-09 00:00:00.000 70852 1
2011-03-09 00:00:00.000 70852 3
I am trying to get output as:
我试图获得输出为:
Date Final_ID
2011-02-25 00:00:00.000 70212_1
2011-02-25 00:00:00.000 70212_2
2011-03-09 00:00:00.000 70852_1
2011-03-09 00:00:00.000 70852_3
I tried doing something like this:
我尝试做这样的事情:
Select Date,Track_ID + '_' + Item# AS Final_ID
From Field_Data
But it gave me following error:
但它给了我以下错误:
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value '_' to data type int.
将 varchar 值“_”转换为数据类型 int 时,消息 245,级别 16,状态 1,第 1 行转换失败。
Can anyone help me on how to do this?
任何人都可以帮助我如何做到这一点?
回答by JNK
You need to cast the INT
fields as varchar
:
您需要将INT
字段转换为varchar
:
Select Date,CAST(Trakc_ID as varchar(20)) + '_' + CAST(Item# as varchar(20)) as Final_ID
From Field_Data
回答by RJB
Heads up for any new page visitors, in SQL Server 12+, there's a CONCAT
function available.
注意任何新页面访问者,在 SQL Server 12+ 中,有一个CONCAT
可用的功能。
SELECT CONCAT([Date], [TrackId], '_', [ItemNumber]) AS FinalId
FROM FieldData