views:

337

answers:

1

Have an image field and want to insert into this from a hex string:

insert into imageTable(imageField) 
values(convert(image, 0x3C3F78...))

however when I run select the value is return with an extra 0 as 0x03C3F78...

This extra 0 is causing a problem in another application, I dont want it.

How to stop the extra 0 being added?

The schema is:

CREATE TABLE [dbo].[templates](
    [templateId] [int] IDENTITY(1,1) NOT NULL,
    [templateName] [nvarchar](50) NOT NULL,
    [templateBody] [image] NOT NULL,
    [templateType] [int] NULL)

and the query is:

insert into templates(templateName, templateBody, templateType) 
values('I love stackoverflow', convert(image, 0x3C3F786D6C2076657273696F6E3D.......), 2)

the actual hex string is quite large to post here.

+1  A: 

This is correct for 0x0: each pair of digits makes one byte so 0x00 has the value stored

When I run SELECT convert(varbinary(max), 0x55) I get 0x55 out on SQL Server 2008. SELECT convert(varbinary(max), 85) gives me 0x00000055 which is correct is 85 is a 32 bit integer

What datatype are you casting to varbinary?

Edit: I still can't reproduce using image not varbinary

Some questions though:

  • is this an upgraded database? What is the compatibility level?
  • why use image: use varbinary(max) instead
  • what happens when you change everything to varbinary?
gbn
I select an existing value it return 0x3C3F78... and then insert it as a new record. Then selecting the new one return 0x03C3F78.... where did the leading zero come from? It's causing an error elsewhere in an application.
rotary_engine
@rotary_engine: what is the *exact* SQL you are running please and the table schema.
gbn
updat to include the schema and sql but the actual hex value is way too big to post here...
rotary_engine
thanks for your help. image is not my choice and not going to upgrade all the instances just for this. however ended up using some c# code to convert the data into a byte array and insert into database.
rotary_engine