问题
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