difference between hex constants and decimal constants in SQL server

▼魔方 西西 提交于 2019-12-11 07:16:21

问题


As a follow up on insert control characters in nvarchar or varchar from SQL script? :

What is the difference between the 0x prefixed hexadecimal constants and the decimal ones in the below SQL script?

It looks like the 0x prefixed ones don't deliver integers. I'm probably in for another duh moment this evening, so please enlighten me (:

select 
  char(0x64) charx64, 
  char(0100) char100, 
  nchar(0x64) ncharx64, 
  nchar(0100) nchar100, 
  char(0x6564) charx6564, 
  char(025956) char25956, 
  nchar(0x6564) ncharx6564, 
  nchar(025956) nchar25956, 
  0x64 x64, 
  0100 d100, 
  0x6564 x6564, 
  025956 d25956, 
  cast(0x64 as varchar) x64varchar, 
  cast(0100 as varchar) d100varchar, 
  cast(0x6564 as varchar) x6564varchar, 
  cast(025956 as varchar) d25956varchar, 
  cast(0x64 as nvarchar) x64nvarchar, 
  cast(0100 as nvarchar) d100nvarchar, 
  cast(0x6564 as nvarchar) x6564nvarchar, 
  cast(025956 as nvarchar) d25956nvarchar, 
  null
;

(the null is there so it was easier to generate this statement)

Result:

C:\bin>"C:\Program Files\Microsoft SQL Server\110\Tools\Binn\SQLCMD.EXE" -S .\SQLEXPRESS -E -i hex-versus-decimal.sql 
charx64 char100 ncharx64 nchar100 charx6564 char25956 ncharx6564 nchar25956 x64  d100        x6564  d25956      x64varchar                     d100varchar                    x6564varchar                   d25956varchar                  x64nvarchar                    d100nvarchar                   x6564nvarchar                  d25956nvarchar                            
------- ------- -------- -------- --------- --------- ---------- ---------- ---- ----------- ------ ----------- ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------ ------------------------------ -----------
d       d       d        d        NULL      NULL      ?          ?          0x64         100 0x6564       25956 d                              100                            ed                             25956                          d                              100                            ?                              25956                                 NULL

(1 rows affected)

回答1:


For MS SQL server, 0x constants are binary literals, not integers (more on binary and varbinary types). When you call char() and nvarchar() on them, they are converted to integers (as if they were big-endian integer representations, if I remember correctly). When you cast them to varchar/nvarchar, they're interpreted as bytes of ANSI- or UCS2-encoded text.



来源:https://stackoverflow.com/questions/20749961/difference-between-hex-constants-and-decimal-constants-in-sql-server

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