Concate Primary Keys in SQL

让人想犯罪 __ 提交于 2019-12-13 22:20:04

问题


I want to concate Primary Keys of multiple tables in SQL directly. 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.

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

where CID , RID and CGID are the Primary Keys of three SQL Tables.

How it skipped the string part in query ?

Any help would be highly appreciated.

Updated

For Example : The Values of CID , RID and CGID are 3 , 4, 3 respectively. It should be 3-4-3 but the result is 10.


回答1:


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.

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():

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

CONCAT() knows that everything should be a string.




回答2:


Try this

SELECT 5 + '-' +  8

The output is 13. I must admit, that I did not expect this...

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. As the single hyphen is casteable to int implicitly, this returns the summa of your values...

The solution, as pointed out by others is either a cast of your column values to a string type or the usage of CONCAT




回答3:


I would need to see output, but I am assuming, some ID is stored as int and it is being counted, so you should use

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


来源:https://stackoverflow.com/questions/38328695/concate-primary-keys-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!