Thursday, August 21, 2008

Right Justify Character data using SQL:

There is no "right-justify" string function built into SQL, but it can still be done: Taking a character string of variable size and right-justifying within a target column containing a maximum of 12 characters. The example below does a bit more but it illustrates well what can be done, effectively concatenating blanks (up to 12) for a length of 12 - the length of the source column.

INSERT INTO TARGET_TABLE
SITE_CODE_RIGHT_JUSTIFED
SELECT
SUBSTR(' ', 1, 12 -
LENGTH( TRIM( CHAR_COLUMN_NAME)))
|| TRIM( CHAR_COLUMN_NAME )
FROM TABLE
FROM SOURCE_DATA

No comments: