I am developing a C# application in my company.
The application uses a SQL Server database via ADO .Net.
The application uses the ADO .Net data provider for SQL Server shipped with the .Net framework 4.
We are facing a problem when inserting a string programmatically into a varchar field.
Example
Let’s consider the database table named MY_TABLE with the following columns :
- MY_FIRST_COL int
- MY_SECOND_COL varchar(250)
I insert a record (REC1) into MY_TABLE by executing the following SQL query within SS Management Studio :
insert into MY_TABLE (1, "");
Then I select REC1 by using SSMS.
Then I copy the string contained in MY_SECOND_COL field.
Then I paste the string into Notepad++.
I notice the string is made up of 0 characters.
OK it makes sense !
Now I insert programmatically a record (REC2) into MY_TABLE by using an SqlCommand object.
Here is the string contained in the CommandText property :
insert into MY_TABLE (@p0, @p1);
Here are some values contained in properties of the SqlParameter object corresponding to the second parameter :
- DbType : System.Data.DbType.AnsiStringFixedLength
- Direction : Input
- IsNullable : false
- ParameterName : “@p1”
- Precision : 0
- Scale : 0
- Size : 0
- SqlDbType : Char
- Value : “”
Then I select REC2 by using SSMS.
Then I copy the string contained in MY_SECOND_COL field.
Then I paste the string into Notepad++.
I notice the string is made up of 250 characters.
Why ?
Any help will be greatly appreciated
That’s your problem. You want
VarChar.Chars are fixed width strings, padded with spaces.SqlDbType: