This is not as simple as it may appear. I have struggled for hours and googled to no avail.
I want to produce a single column that always has a length of 30 characters, so if the column only contains 2 characters, the other 28 characters should be empty spaces.
I am trying to get two different columns into a single one, as follows:
select FirstName + LastName as FullName
I want to get the following result:
That means that the first row will have 7 visible characters (Michael), followed by 8 spaces, followed by 6 visible characters (Jordan), followed by 9 spaces. That makes a total of 30 characters. The second row will have 5 visible characters (Magic), followed by 10 spaces, followed by 7 visible characters (Johnson), followed by 8 spaces. The third row will have 5 visible characters (Larry), followed by 10 spaces, followed by 4 visible characters (Bird), followed by 11 characters.
The length of both columns will always vary, so I am looking for code that works regardless of the length. This means that it always adds the correct number of blank spaces after the first name. As you probably noticed, it is always 15 characters (either visible or empty) for the first name and another 15 characters (either visible or empty) for the last name.
Does anyone know how to do this? Thanks in advance!
Use char()
:
select concat(convert(char(15), firstname), convert(char(15), lastname))
The char()
type automatically pads strings with spaces, so no more work is necessary. This also has the nice feature that if the first or last names are too long, only the first 15 characters are used.
This is explicitly documented for len()
(to conform with the standard, I think):
Returns the number of characters of the specified string expression, excluding trailing spaces.
Followed by this recommendation:
Note
To return the number of bytes used to represent an expression, use the DATALENGTH function.
Here is a db<>fiddle.
SQL Server discounts the spaces when measuring the length. So, in the length of the above, you will get 21 and 20. To see the length without removing the tailing spaces, use datalength()
.