简体   繁体   English

在SQL中串联主键

[英]Concate Primary Keys in SQL

I want to concate Primary Keys of multiple tables in SQL directly. 我想直接在SQL连接多个表的Primary Keys I used below query to concate three primary keys with a hyphen between them but the SQL skipped the hyphen and sum up the primary keys and result in a single value. 我在下面的查询中使用了三个主键,并将它们之间的连字符连接起来,但是SQL跳过了连字符并求和了主键并得出一个单一值。

  SELECT CID + '-' + RID + '-'+  CGID As [IdCombination] ...    

where CID , RID and CGID are the Primary Keys of three SQL Tables. 其中CID,RID和CGID是三个SQL表的Primary Keys

How it skipped the string part in query ? 如何跳过查询中的string部分?

Any help would be highly appreciated. 任何帮助将不胜感激。

Updated 更新

For Example : The Values of CID , RID and CGID are 3 , 4, 3 respectively. 例如:CID,RID和CGID的值分别为3、4、3。 It should be 3-4-3 but the result is 10. 应该是3-4-3,但结果是10。

What is happening? 怎么了? Remember that + means both addition and string concatenation. 请记住, +表示加法和字符串连接。 It so happens that - can be interpreted as a number (like -0 ), so SQL Server prefers to interpret the + as addition. 碰巧-可以解释为数字(如-0 ),因此SQL Server倾向于将+解释为加号。

Normally, when you do this type of operation, the separation character cannot be interpreted as a number, and you just get an error. 通常,当您执行这种类型的操作时,分隔符不能解释为数字,而只会出现错误。 I am amused that you don't get an error in this case. 我很高兴您在这种情况下没有收到错误。

One method is to explicitly cast the values as strings: 一种方法是将值显式转换为字符串:

SELECT CAST(CID as VARCHAR(255)) + '-' + CAST(RID +  as VARCHAR(255)) '-'+  CAST(CGID  as VARCHAR(255)) As [IdCombination] 

In SQL Server 2012+, you can do this more simply using CONCAT() : 在SQL Server 2012+中,您可以使用CONCAT()更简单地执行此操作:

SELECT CONCAT(CID, '-', RID, '-', 'CGID) As [IdCombination] 

CONCAT() knows that everything should be a string. CONCAT()知道所有内容都应该是字符串。

Try this 尝试这个

SELECT 5 + '-' +  8

The output is 13. I must admit, that I did not expect this... 输出为13。我必须承认,我没想到这一点...

And now try this 现在试试这个

SELECT CAST('-' AS INT)

The result is 0. As your select starts with an INT, SQL Server tries to do a summa of int values. 结果为0。由于选择以INT开头,因此SQL Server尝试对int值进行求和。 As the single hyphen is casteable to int implicitly, this returns the summa of your values... 由于单个连字符可以隐式转换为int,因此将返回值的总和...

The solution, as pointed out by others is either a cast of your column values to a string type or the usage of CONCAT 其他人指出的解决方案是将列值转换为字符串类型,或者使用CONCAT

我将需要查看输出,但是我假设一些ID以int形式存储并且正在计算中,因此您应该使用

SELECT Cast(CID as Varchar(50)) + '-' + Cast(RID as Varchar(50)) + '-'+  Cast(CGID as Varchar(50)) As [IdCombination]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM