2

Custom string formatting in SQL Server 2008

DECLARE @a varchar(11)
SET @a='40010510120'

Result should be

|4|0|0|1|-|0|5|1|-|0|1|-|2|0|

or

4 0 0 1 - 0 5 1 - 0 1 - 2 0

How can I do this?

Thanks in advance!

3
  • 1
    Have you tried anything? loops? string manipulations? Commented Dec 3, 2013 at 2:58
  • @YuriyGalanter Thanks for quick reply. I did not try loop, coz i am not good at loop, but I am searching is there any custom formatting in sql server where I can define my format. Commented Dec 3, 2013 at 3:02
  • SQL Server 2012 now has a FORMAT function, but that's a new feature in the 2012 release, not available in earlier versions Commented Dec 3, 2013 at 5:56

2 Answers 2

1

That's quite a lot of concatenation but it will work fine if the string length is 11:

DECLARE @a varchar(11)
SET @a='40010510120'

SELECT '|' + SUBSTRING(@a, 1, 1)
    + '|' + SUBSTRING(@a, 2, 1)
    + '|' + SUBSTRING(@a, 3, 1)
    + '|' + SUBSTRING(@a, 4, 1)
    + '|-'
    + '|' + SUBSTRING(@a, 5, 1)
    + '|' + SUBSTRING(@a, 6, 1)
    + '|' + SUBSTRING(@a, 7, 1)
    + '|-'
    + '|' + SUBSTRING(@a, 8, 1)
    + '|' + SUBSTRING(@a, 9, 1)
    + '|-'
    + '|' + SUBSTRING(@a, 10, 1)
    + '|' + SUBSTRING(@a, 11, 1)
    + '|'

You can turn it into a function:

CREATE FUNCTION dbo.CustomFormat(@a NVARCHAR(11))
RETURNS varchar(29)
AS
BEGIN
RETURN '|' + SUBSTRING(@a, 1, 1)
        + '|' + SUBSTRING(@a, 2, 1)
        + '|' + SUBSTRING(@a, 3, 1)
        + '|' + SUBSTRING(@a, 4, 1)
        + '|-'
        + '|' + SUBSTRING(@a, 5, 1)
        + '|' + SUBSTRING(@a, 6, 1)
        + '|' + SUBSTRING(@a, 7, 1)
        + '|-'
        + '|' + SUBSTRING(@a, 8, 1)
        + '|' + SUBSTRING(@a, 9, 1)
        + '|-'
        + '|' + SUBSTRING(@a, 10, 1)
        + '|' + SUBSTRING(@a, 11, 1)
        + '|'
END

SELECT dbo.CustomFormat('40010510120')
Sign up to request clarification or add additional context in comments.

Comments

1

Try this...

DECLARE @a varchar(11)
SET @a='40010510120'

Declare @i as int
set @i=1
declare @output as varchar(29)
set @output=''
while @i<=LEN(@a)
begin

 if @i=5 or @i=8 or @i=10
    set @output= @output + '|-|' + SUBSTRING(@a,@i,1)
 else if @i=LEN(@a)
    set @output= @output + '|' + SUBSTRING(@a,@i,1) + '|'
 else
    set @output= @output + '|' + SUBSTRING(@a,@i,1)

set @i=@i+1
end
select @a
select @output

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.