a b
a b

Reputation: 57

Using a SQL function to pad strings with spaces

Is it inefficient to use a user defined function to pad spaces? I have a padding function that I'd more intuitive than using the built in REPLICATE function but I am afraid it is introducing inefficiency into the code.

The padding must be done in SQL.

Upvotes: 2

Views: 10557

Answers (1)

Zohar Peled
Zohar Peled

Reputation: 82474

You can use RIGHT or LEFT depending on the padding direction.
For example:

SELECT RIGHT('11111' + originalString, 5) 

This will pad your string with on the left with 1s to make a 5 letters string. (I've used 1s instead of spaces so it will be easy to read. For spaces you can use the SPACE function:

SELECT RIGHT(SPACE(5) + OriginlString, 5)

to pad to the right you can do this:

SELECT LEFT(OriginalString + SPACE(5), 5) 

or simply convert to char as suggested by Gordon Linoff in the comments

Upvotes: 4

Related Questions