nvarchar padded strings
Sunday, July 30th, 2006Here’s my little mystery of the day that took me an hour to figure out:
I have a table called EQUIPMENT with a column called SITE nvarchar(50). For some strange reason the results I’m getting from ADO.net is a string padded to full 50 characters. Now, only nchar(50) does that. I checked with Query Analyzer:
SELECT SITE, LEN(SITE) FROM EQUIPMENT
RO, 2
A bit of search with Google showed that LEN actually trims off trailing whitespace, so the function above doesn’t tell me anything. I changed my query a bit:
SELECT SITE, LEN(SITE) FROM EQUIPMENT WHERE SITE='RO'
RO, 2
Surely there are no padded strings in the database. I looked up the SQL books online, which confirmed that nvarchar is not padded with spaces. What’s going on here?
One more query:
SELECT SITE + '***', LEN(SITE) FROM EQUIPMENT WHERE SITE='RO'
RO ***, 2
What the *&^%#@! SQL Server implements the = comparion by trimming off trailing whitespace for nvarchar. But how did the column get spaces in the first place?
Suddenly it dawned on me the original column was nchar(50), and I had changed it to nvarchar(50) after I had imported the data. So the padding on the original nchar(50) stays.
