0

I am trying to insert a string into a char(20) column in my SQL Server database.

I set the string to be equal to a value and then add it to a parameter

thisstring = "1914"
cmd.Parameters.AddWithValue("@code", thisstring)

However every time I try it ends up looking like this in the database

picture

I need it to look like the 1913, 000000, 000001 ones.

When I try to pad the string with spaces

thisstring= thisstring.PadLeft(20, " ")

or

thisstring = "     " & thisstring

I am getting

String or binary data would be truncated

even if the field wasn't 20 characters total

What am I doing wrong?

Edit*** here is the column in SQL Server

http://imgur.com/BbV6VQv

3
  • what is the SQL or stored procedure call with cmd, i.e. cmd.CommandText? Commented Jun 21, 2013 at 19:10
  • thisstring= thisstring.PadLeft(20, " ") should have worked. Can you double check the parameter definition. This could be different than the table definition. Commented Jun 21, 2013 at 19:10
  • cmd = New SqlCommand(strSQL, conn) and the execute is cmd.ExecuteNonQuery() Commented Jun 21, 2013 at 19:12

1 Answer 1

1

I am not absolutely sure, but I think the problem lies in the AddWithValue.
While convenient this method doesn't allow to specify the exact datatype to pass to the database engine and neither the size of the parameter. It pass always an nvarchar parameter for a C# UNICODE string.

I think you should try with the standard syntax used to build a parameter

Dim p = new SqlParameter("@code", SqlDbType.Char, 20)
p.Value = thisstring.PadLeft(20, " ")

See this very interesting article on MSDN

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.