1

How to add substring in SQL ?

DECLARE @ssn varchar(11)
SELECT @ssn = '123456789'

Actually, i have the value in my database as 123-45-6789

I want to do it one query to get the output as 12-456789

Expected output is 12-3456789

1
  • Is it on purpose, that the "3" is missing in your line "I want to do it in one query..."? Commented Dec 8, 2015 at 19:41

2 Answers 2

2

If you want to add a hyphen, you can use stuff():

select @ssn = stuff(@ssn, 3, 0, '-')

EDIT:

Removing a hyphen is quite similar:

select @ssn = stuff(@ssn, 7, 1, '')
Sign up to request clarification or add additional context in comments.

1 Comment

it works .. but i did some change in my actual post. could you please help me with that
1

Try it with STUFF:

EDIT: Your follow-up question:

DECLARE @ssn varchar(100);
SELECT @ssn = '123-45-6789';

SELECT STUFF(REPLACE(@ssn,'-',''),3,0,'-');

The old question:

DECLARE @ssn varchar(11);
SELECT @ssn = '123456789';

SELECT STUFF(@ssn,3,0,'-');

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.