Question

I have a TELEPHONE_NUMBER as a varchar like this:

Value : "1112223344"

And I need to add "-" to the value like this:

111-222-33-44

So how can I add - to my telephone number value in my SQL Server stored procedure?

CREATE PROCEDURE SP_TELEPHONE_NUMBER
   (@TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
   INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
   VALUES(@TELEPHONE_NUMBER)
END
Was it helpful?

Solution

Just an alternative:

select SUBSTRING('1112223344',1,3)+'-'+
       SUBSTRING('1112223344',4,3)+'-'+
       SUBSTRING('1112223344',7,2)+'-'+
       SUBSTRING('1112223344',9,2)

In your case:

CREATE PROCEDURE SP_TELEPHONE_NUMBER
   (@TELEPHONE_NUMBER VARCHAR(4000))
AS
BEGIN
   INSERT INTO DOSYA_ARSIV(TELEPHONE_NUMBER)
   VALUES
   (
       SUBSTRING(@TELEPHONE_NUMBER,1,3)+'-'+
       SUBSTRING(@TELEPHONE_NUMBER,4,3)+'-'+
       SUBSTRING(@TELEPHONE_NUMBER,7,2)+'-'+
       SUBSTRING(@TELEPHONE_NUMBER,9,2)
   )
END

As noobob has mentioned in his comment, you may have this as an INT type (INT,BIGINT or something similar) and just handle the way it is displayed in the front end. For instance in C# you would have it as:

TELEPHONE_NUMBER.ToString("###-###-##-##");

Another comment would be that defining the expected argument as VARCHAR(4000) is way too much. Though it might not be very bad, it is a good point to define arguments or variables as close to expected input as you can. In your case i would say that something like VARCHAR(30) would be enough.

OTHER TIPS

Use STUFF function in the MS SQL server

SET @TELEPHONE_NUMBER=STUFF(STUFF(STUFF(@TELEPHONE_NUMBER,4,0,'-'),8,0,'-'),11,0,'-')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top