Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Strings Padded with Whitespace on Insert - why?

when i tried to insert some data into the SQL Server there was these extra characters

for example my textBox1.text == "SAMPLE"
then this was the code

string qry = "insert into FinalImages (FinalImageName, Date) values(@FinalImageName, @Date)";

SqlConnection c = new SqlConnection(c_string);
//Initialize SqlCommand object for insert
SqlCommand SqlCom = new SqlCommand(qry, c);

SqlCom.Parameters.Add(new SqlParameter("@FinalImageName", SqlDbType.Char, 40)).Value = textBox1.Text;
SqlCom.Parameters.Add(new SqlParameter("@Date", SqlDbType.Char, 40)).Value = DateTime.Now.ToString("MM/dd/yyyy");

but when i check in the tables the record was this "SAMPLE ", it has 34 space characters added
what should be wrong?

like image 697
Ozarraga_AB Avatar asked Mar 02 '12 16:03

Ozarraga_AB


People also ask

How do I get rid of leading white space in SQL?

SQL Server TRIM() Function The TRIM() function removes the space character OR other specified characters from the start or end of a string. By default, the TRIM() function removes leading and trailing spaces from a string.

What is white space in SQL?

What exactly is 'white space'? White space is a character in a string that represents horizontal or vertical space in typography. In other words: tabs, line feeds, carriage returns and, yes, spaces. A white space has character value, just like 'A', 'B' and 'C' have a value.

Does SQL ignore trailing spaces?

Takeaway: According to SQL Server, an identifier with trailing spaces is considered equivalent to the same identifier with those spaces removed.


1 Answers

Don't use SqlDbType.Char, use NVarChar. Char is a fixed-size string, padded with spaces (a terrible monster).

like image 56
usr Avatar answered Nov 15 '22 05:11

usr