November 6, 2010 at 9:20 pm
I'd like to pad an nvarchar field with trailing spaces to make the length a uniform 23. Is there anything
equivalent to what I do in excel as in =A2&REPT(" ",23-LEN(A2))?
Thanks
November 6, 2010 at 10:50 pm
CONVERT(nchar(23), <FieldToConvert>)
Wayne
Microsoft Certified Master: SQL Server 2008
Author - SQL Server T-SQL Recipes
November 7, 2010 at 8:02 am
How about this?
SELECT Col1 + SPACE(32-LEN(Col1))
November 7, 2010 at 11:51 am
Glenn (11/6/2010)
I'd like to pad an nvarchar field with trailing spaces to make the length a uniform 23. Is there anythingequivalent to what I do in excel as in =A2&REPT(" ",23-LEN(A2))?
Thanks
As others have clearly demonstrated, it is certainly possible in a number of ways, but I ask myself: what is the point of using a nvarchar field? Use a nchar(23) field, so the padding is automatically performed for you. I'm not sure, but this can be an optimization for your database engine, as it doesn' have to check the length of your variable field anymore.
Need an answer? No, you need a question
My blog at https://sqlkover.com.
MCSE Business Intelligence - Microsoft Data Platform MVP
November 7, 2010 at 12:14 pm
ColdCoffee (11/7/2010)
How about this?
SELECT Col1 + SPACE(32-LEN(Col1))
That can result in a string longer than 23 characters if there are already trailing spaces.
Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability
November 9, 2010 at 1:17 pm
This should fix that method Gail, although I suspect a convert would yield better performance.
SELECT Left(Col1 + SPACE(32), 32)
_______________________________________________________________
Need help? Help us help you.
Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.
Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.
Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/
Viewing 6 posts - 1 through 5 (of 5 total)
You must be logged in to reply to this topic. Login to reply