Reputation: 6188
I have a table in which there is one column named:
'eZip' (varbinary(5), null).
Now I am adding value from a web form like this:
cmd.Parameters.Add("@eZip", SqlDbType.VarBinary).Value = BitConverter.GetBytes(int.Parse(txtZip.Text.ToString()));
Its working but instead of putting a valid zip code, it is inserting this into my column:
<Binary data>
What I am doing wrong here?
Upvotes: 1
Views: 1439
Reputation: 7850
I don't think you are doing anything wrong per-se. if you define the field as varbinary you will always see "Binary Data" in SQL Server's management tools, regardless of the data.
Are you sure you don't want just CHAR(n)
OR VARCHAR(n)
for the zip code?
Upvotes: 3
Reputation: 2712
If you can't change the data type of that column, all you need to do is convert the value when you get the data back out. As recommended by others, you should at least change your code to assume that the five bytes are characters, not integers.
Insert the value:
cmd.Parameters.Add("@eZip", SqlDbType.VarBinary).Value = System.Text.Encoding.ASCII.GetBytes(txtZip.Text.ToString());
Retrieve the value in SSMS tools:
SELECT CONVERT(VARCHAR(5), [eZip]) AS [eZip] FROM @zip_table;
Retrieve the value from a DataRow dr
in C#:
System.Text.Encoding.ASCII.GetString(dr["eZip"]);
If you can change the column to a CHAR(5) or VARCHAR(5), then no conversion will be necessary.
Upvotes: 1