February 27, 2009

SQL SERVER: REPLICATE function

Today i read SQLAuthority.com, and I found that one developer has this issue. Lets see that problem as well as the solution for the same.

There is one numeric column. User needs to make sure that all data should be of same size. Like "17.00,12.00,8.17,4.44", these all should be "17.00,12.00,08.17,04.44" like that.

So I found REPLICATE function of SQL SERVER, to fix this.

How to use REPLICATE function?

REPLICATE ("string that you want TO append" ,"INTEGER VALUE" )

FIRST parameter, i need TO SET the CHARACTER, which will append it BEFORE the NUMBER.

SECOND parameter, how many times this CHARACTER should be ADD TO the NUMBER.

Example:

DECLARE @t AS NUMERIC(8,2)
SELECT @t = 08.2
SELECT Cast(Replicate(0,6-Len(@t)) AS VARCHAR(5)) + Cast(@t AS VARCHAR(5))

Here I specify that there should be 5 length. In this case 8.23 has four digit, so this will add one "0" to this number.

We can append any character by just changing the First Parameter, String value.

Let me know your suggestions

1 comment:

  1. That's interesting, though I prefer:

    DECLARE @t AS NUMERIC(8,2);
    set @t = 08.2;
    SELECT RIGHT('000000'+Cast(@t AS VARCHAR(5)),6);

    ReplyDelete