0

I need to add spaces to the end of a column I have called NPI (nvarchar(20)). NPI is always 10 digits, but the requirements for the report want the first 10 digits to be the NPI followed by 10 spaces (text file formatting issues I assume). I have tried the following:

cast([NPI] as nvarchar(20)) + '          '
cast([NPI] as nvarchar(20)) + Space(10)

However, the result set does not change. It just shows the 10 digit NPI and spaces aren't included.

3 Answers3

2

It sounds like you are actually using SQL Server instead of MySQL. VARCHAR() is for variable length strings and it will trim end whitespace. Cast instead to char/nchar for the desired output. It won't look like it in SSMS, so check datalength to confirm nchar(20) = 20 bytes * 2 for unicode.

SELECT CAST([NPI] AS NCHAR(20)) AS formattedNPI, 
DATALENGTH(CAST([NPI] AS NCHAR(20))) AS confirmation
FROM your_table
dfundako
  • 8,022
  • 3
  • 18
  • 34
  • Just an echo, SSMS is likely formatting your output, so the results in the SSMS results pane may not appear to have the spaces. – Twelfth Mar 16 '18 at 14:57
  • Thank you!!! For anyone else, this may not show in result set, but if you export to text or csv, or copy and paste into query, the spaces will be there. – Gregory Brauninger Mar 16 '18 at 14:57
  • Also, @GregoryBrauninger if you are working with NPI's and need to verify the NPI is valid, go look up Luhn algorithm. – dfundako Mar 16 '18 at 14:58
0

Add the space inside the cast

cast([NPI] + '         ' as nchar(20))

You're right @dfundako, I was fooled by my editor.

This works but I am using MariaDb (MySql) so it's maybe not relevant now.

select concat([NPI] , '         ')
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
0

This seems to work. The '*' is added to show that spaces are present..

print cast([NPI] as nchar(20)) + '*'

Here are a couple of other cheesy ways to add padding...

print substring([NPI] + '                    ',1,20) + '*'

print [NPI] + space(20 - len([NPI])) + '*'
Keith Aymar
  • 876
  • 7
  • 10