I have a 10 Character length values in a column in SQL Server. I need to split that column at fixed length and remove the leading zeros and add a – after each of the values. I am able to split the values by using Substring and converting them to int. It is working well.
However, when I try to concatenate it is failing. Appreciate if you can help.
SELECT TOP 1 R.COL1, CAST(SUBSTRING(R.COL1,1,1) AS int) AS F1,CAST(SUBSTRING(R.COL1,2,5) AS int) AS F2,CAST(SUBSTRING(R.COL1,7,4) AS int) AS F3 CAST(SUBSTRING(R.COL1,1,1) AS int) +'-' +CAST(SUBSTRING(R.COL1,2,5) AS int) +'-' + CAST(SUBSTRING(R.COL1,7,4) AS int) AS finalString FROM MYTABLE R
If the value for COL1 IS 1012950001 the finalString I am expecting is 1-1295-1 however the result I am getting from the above query is 1297 as it is adding all the values. Appreciate if you can help.
Advertisement
Answer
You can’t use the +
operator with a numerical data type and a varchar
that cannot implicitly be converted to that data type. Something like 1 + 'a'
isn’t going to work, as 'a'
isn’t an int
, and can’t be implicitly converted to one.
If you are mixing data types, then use CONCAT
, which implicitly converts each part into a (n)varchar
:
CONCAT({Numerical Expression},'a',{Other varchar Expression})