2

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.

4
  • 2
    What RDBMS are you using? Commented Apr 25, 2015 at 15:00
  • Microsoft SQL Server Commented Apr 25, 2015 at 15:05
  • 2
    I assume you are left padding. Right padding is trivial, because you can just cast the value to a char(). Commented Apr 25, 2015 at 15:21
  • Thanks. What we have is a lot of calls to user defined functions for right and left padding already written to do this and I'm wondering if it is worth replacing it with the suggestions above. Commented Apr 25, 2015 at 16:14

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. What we have is a lot of calls to user defined functions for right and left padding already written to do this and I'm wondering if it is worth replacing it with the suggestions above.
You shold know better then anyone since you know you system best. It's probably possible to replace one udf call ant test performance, and then decide what to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.