insert varbinary value from hex literal in Microsoft SQL Server

en *_*ris 2 sql-server jdbc spring-jdbc jdbctemplate mssql-jdbc

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);
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Gor*_*son 6

CONVERT 函数文档说二进制类型的默认“样式”是0

将 ASCII 字符转换为二进制字节,或将二进制字节转换为 ASCII 字符。每个字符或字节按 1:1 转换。

所以,

SELECT CONVERT(VARBINARY, '0x00173672') AS foo;
Run Code Online (Sandbox Code Playgroud)

返回

foo
--------------------------------------------------------------
0x30783030313733363732
Run Code Online (Sandbox Code Playgroud)

它们是十六进制文字的 ASCII 字节值,而不是十六进制字节本身。为了让 CONVERT解释十六进制文字,您需要使用 style 1,即

SELECT CONVERT(VARBINARY, '0x00173672', 1) AS foo;
Run Code Online (Sandbox Code Playgroud)

返回

foo
--------------------------------------------------------------
0x00173672
Run Code Online (Sandbox Code Playgroud)