insert varbinary value from hex literal in Microsoft SQL Server

六眼飞鱼酱① 提交于 2020-02-24 12:23:05

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/50507385/insert-varbinary-value-from-hex-literal-in-microsoft-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!