Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert varbinary value from hex literal in Microsoft SQL Server

I have a SpringBoot app, where I use jdbcTemplate to insert a row to a mssql

int numOfRowsAffected = remoteJdbcTemplate.update("insert into dbo.[ELCOR Resource Time Registr_]  "
                + "( [Entry No_], [Record ID], [Posting Date], [Resource No_], [Job No_], [Work Type], [Quantity], [Unit of Measure], [Description], [Company Name], [Created Date-Time], [Status] ) "
                + " VALUES (?,CONVERT(varbinary,?),?,?,?,?,?,?,?,?,?,?);",

                ELCORResourceTimeRegistr.getEntryNo(), 
                ELCORResourceTimeRegistr.getEntryNo()), 
                ELCORResourceTimeRegistr.getPostingDate(),
                ELCORResourceTimeRegistr.getResourceNo(), 
                jobNo,
                ELCORResourceTimeRegistr.getWorkType(), 
                ELCORResourceTimeRegistr.getQuantity(),
                ELCORResourceTimeRegistr.getUnitOfMeasure(), 
                ELCORResourceTimeRegistr.getDescription(),
                ELCORResourceTimeRegistr.getCompanyName(), 
                ELCORResourceTimeRegistr.getCreatedDate(), 
                0);

the value of ELCORResourceTimeRegistr.getEntryNo() is a String with the value 0x00173672

but what is inserted in the DB is <30007800 30003000 31003700 33003600 37003200>

ELCORResourceTimeRegistr.getEntryNo().getClass().getCanonicalName() => java.lang.String
like image 620
en Peris Avatar asked Oct 18 '25 10:10

en Peris


1 Answers

The documentation for the CONVERT function says that the default "style" for binary types is 0:

Translates ASCII characters to binary bytes, or binary bytes to ASCII characters. Each character or byte is converted 1:1.

So,

SELECT CONVERT(VARBINARY, '0x00173672') AS foo;

returns

foo
--------------------------------------------------------------
0x30783030313733363732

which are the ASCII byte values of the hex literal, not the hex bytes themselves. In order for CONVERT to interpret the hex literal, you need to use style 1, i.e.

SELECT CONVERT(VARBINARY, '0x00173672', 1) AS foo;

which returns

foo
--------------------------------------------------------------
0x00173672
like image 113
Gord Thompson Avatar answered Oct 22 '25 00:10

Gord Thompson