You must Sign In to post a response.
  • Category: SQL Server

    Leading zero in string

    leading zero in string.
    i.e. string contain hyphen(-).


    Example:

    input.
    1-1-12,
    10-2-1,
    1-2-3


    Output

    01-01-12,
    10-02-01,
    01-02-03
  • #767438
    What is your requirement? Can you explain the issue little bit clearly. So that we can try to solve it.
    By Nathan
    Direction is important than speed

  • #767441
    i want convert the the string like..

    1-1-12 -->01-01-12,
    1-1--->01-01,
    1-->01

  • #767443
    Can you please explain you requirement little much better ?

  • #767450
    Hi,
    Try this:

    string szInput = "1-1-12";
    string szOutput = "";
    foreach (string szValue in szInput.Split('-'))
    {
    if (szValue.Length < 2)
    szOutput = szOutput.Trim() == "" ? (szValue.PadLeft(szValue.Length + 1, '0').Trim() + "-") : (szOutput.Trim() + szValue.PadLeft(szValue.Length + 1, '0').Trim() + "-");
    else
    szOutput = szOutput.Trim() == "" ? (szValue + "-") : (szOutput + szValue + "-");
    }
    if (szOutput.EndsWith("-"))
    szOutput = szOutput.Remove(szOutput.LastIndexOf("-"));
    Console.WriteLine(szOutput);

  • #767586
    If you want to achieve it in sql server. you can use code like below

    declare @b as varchar(255)
    set @b = ''
    declare @a as varchar(100)
    set @a = '-1-11-1-2-';--assign your value here
    with tbl_for_csv as
    (
    select left(@a, charindex('-',@a) - 1) as val,
    stuff(@a +'-',1,charindex('-',@a),'') as col
    union all
    select cast(left(col, charindex('-',col) - 1) as varchar(100)),
    stuff(col,1,charindex('-',col),'') from tbl_for_csv
    where col <> ''
    )

    select @b = @b + case when len(val) < 2 then replicate('0',2-len(val))+ Val else val end + '-' from tbl_for_csv

    select left(@b,len(@b)-1)

    Many Thanks
    Tejinder Singh Barnala
    /*I have the simplest tastes. I am always satisfied with the best*/


Sign In to post your comments