Question

I am using SQL Server 2008, Visual Web Developer 2012 and .net 4.0. I created a table in SQL Server and added some columns to it. I gave some columns the datatype nchar(10).

Now my problem is that when I insert string of less than 10 characters as a value of the column type nchar(10) and when I fetched the value it inserts blank spaces to complete the 10 character string.

Means if I insert "a" into column of type nchar(10), then when I fetch the value again I get back: "a "

How can I resolve this issue ?

No correct solution

OTHER TIPS

You can do like this to trim the whitespaces:

SELECT RTRIM(CAST(col As NVARCHAR(10))) FROM test

Check out SQLFIDDLE

define the string as nvarchar(10) it will work fine

If you don't want to change data type, then you will need to TRIM the space from the output

SELECT
   RTRIM("a      ") AS ColumnName
FROM MyTable

But this means every time you have to do this every place you are using the column. It is better to user VARCHAR(10) or NVARCHAR(20) where VAR... means variable length. So if your string is not up to 10 characters, spaces are not added

Final SQL

SELECT
   RTRIM(ColumnName) AS ColumnName
FROM myTable
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top