0

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.

8
  • 2
    Don't cast them to int if you don't want + to treat them as ints Commented Jun 20, 2020 at 14:05
  • Converting, however, is the easiest way to remove the leading zeroes though, @DaveCosta . The alternative would be using PATINDEX and STUFF. Commented Jun 20, 2020 at 14:10
  • Welcome to data type precedence. Commented Jun 20, 2020 at 14:31
  • @Larnu doesn't SQL Server have TRIM()? Commented Jun 20, 2020 at 16:46
  • Yes, however, how does that help remove leading zeroes, @DaveCosta ? Commented Jun 20, 2020 at 16:53

2 Answers 2

3

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})
Sign up to request clarification or add additional context in comments.

Comments

0

You can use concat method to concatenate the substring value

select 
concat(CAST(SUBSTRING('1012950001',1,1) AS int), '-', 
CAST(SUBSTRING('1012950001',2,5) AS int), '-', 
CAST(SUBSTRING('1012950001',7,4) AS int)) AS finalString

This will give you the expected result '1-1295-1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.