Saturday, August 07, 2010

SQL Pad Left Functionality (Oracle / SQL Server)

If you needs to pad a column value with a character or symbol in order to conform the resulting value to some standard. For example, a company may represent their stores by a maximum of 4 digits and each character in that 4-digit store number must contain a value as to not be confused with any other values.. In other words, store #99 would be represented as 0099 instead of just 99.

This is not uncommon practice. Often times, similar functionality is required when pulling data from the mainframe where “super keys” are paramount. Our good friends at MS have set up SQL Server so that this is universally simple. The code snippet in its basic form looks like this:
SQL function
RIGHT('0000' + CategoryID, 4)

Out Put
00001
00002
00003
00004
00020
00022

 This is straightforward. Use the RIGHT function by concatenating the first parameter to a set number of padding characters and the column name in your table. Be sure to CAST that column as a string data type if pulling a numeric field. Then, for the RIGHT functions second parameter, make its value the same number of character spaces required for your final value.
Oracle just had to be difficult. In order to conduct the same operation using PL/SQL you must use a function, which I am still not sure how it completely works behind the scenes. The syntax is as follows:

SELECT to_char([COLUMN NAME],'FM0000') AS result FROM table;

Update
Recently a reader posted the use of the Oracle function LPAD, which is much cleaner than the use of the FM function and works better than the SQL Server function. The syntax would be

SELECT LPAD('Test', 8, '0') AS result FROM dual;
This LPAD function has been relevant since 8i.

Conclusion
Each of the code snippets above will provide a conformed look at a column value. SQL Server’s method seems to be a little more cut n’ dry than PL/SQL’s but they both get the job done.

Another great source for Oracle functions can be found at http://www.techonthenet.com/oracle/functions/lpad.php

1 comment:

  1. I would like to exchange links with your site asmaqureshi.blogspot.com
    Is this possible?

    ReplyDelete