Using IBM i? Need to create Excel, CSV, HTML, JSON, PDF, SPOOL reports? Learn more about the fastest and least expensive tool for the job: SQL iQuery.
I have a file with a field that I needed to right-adjust the character values. These values are of various lengths, and in many records they were left-adjusted while in others they were correctly right-adjusted.
After correcting the program that was writing them left-adjusted, I needed to fix the existing records. I was surprised to discover that there's no simple function to right-adjust a value in SQL. I was thinking I would have to write an RPG to run through all the records and do EvalR myField = %trim(myField);
But then I found a post somewhere (from Birgitta Hauser, I think) that showed how to do it in SQL. This is what I ended up with:
update myLib/myFile set myField = space(length(myField) - length(trim(myField))) concat trim(myfield) where myField <> ' '
Voila! Hope maybe someone else finds this useful too.
The SPACE function creates a string of blanks of the length specified? Interesting.
I looked up SPACE in my SQL book and it's not even listed, but it seems to work well!
So not the IBM SQL Reference, then: http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/topic/db2/rbafzscaspace.htm. It's an ANSI scalar function. Works in SQL Server (T-SQL), too.
Pondering . . . might this have better performance?
update myLib/myFile
set myField = RIGHT(SPACE(LENGTH(myField)) + TRIM(myField), length(myField))
where myField <> ' '
Either way, maybe add AND RIGHT(myField, 1) = ' ' to the WHERE clause, to avoid null updates.