SQL Tutorial - SQL Pad Leading Zeros
In order to sql pad leading zeros, sql developers use sql string concatenation and sql string functions LEFT and RIGHT.
LEFT and RIGHT sql string functions enable sql developers to take left part of a string variable or column, or extract right part of a string.
A parameter enables the extracted string to be in a definite length.
Here in this t-sql tutorial, you will find methods for sql padding zeros in your t-sql codes.
Then I will give some more information about SQL Server SQL String functions like RIGHT, LEFT and REPLICATE here.
The last section of the sql tutorial on padding with zeros or with any other characters will display t-sql codes of two user defined sql zero padding functions.
These functions are udfLeftSQLPadding and udfRightSQLPadding for sql padding from left or start of the string and sql padding from the right or end of the string.
Now let's go deeper with each sql function used for sql paddding zeros.
SQL string RIGHT function has the following syntax :
The SQL Right function returns characters beginning from the end of the string expression in "length" argument value characters long.
Just like the Right function, sql string function Left() has the same syntax.
On the other hand, just the opposite of Right function, SQL Left function returns length argument value characters long part of the string expression beginning from the start.
Here is a sql string function example using Right function and Left function.
Another sql string function which is used to sql pad leading zeros is the SQL Replicate string function.
The string Replicate function has the following t-sql syntax :
Replicate sql function returns a new string value which has i times concatenated value of the character expression.
Here is a sql Replicate function example:
Here how we can use udfLeftSQLPadding user defined function for zero padding in SQL codes.
The output of the above sample SQL function will be as follows
SQL programmers can create an other user defined SQL function for right padding or adding characters to the tail of the input value to fix the output length.
Following SQL Select statement shows what will be the output of udfRightSQLPadding function.
As seen below, the output length is 10 as passed to the SQL function and missing characters are added to the end of the input expression.