Hex characters in varchar() is actually ascii. Need to decode it

Deadly 提交于 2020-01-03 11:46:50

问题


This is such an edge-case of a question, I'd be surprised if there is an easy way to do this.

I have a MS SQL DB with a field of type varchar(255). It contains a hex string which is actually a Guid when you decode it using an ascii decoder. I know that sounds REALLY weird but here's an example:

The contents of the field: "38353334373838622D393030302D343732392D383436622D383161336634396339663931"

What it actually represents: "8534788b-9000-4729-846b-81a3f49c9f91"

I need a way to decode this, and just change the contents of the field to the actual guid it represents. I need to do this in T-SQL, I cannot use .Net (which if I could, that is remarkably simple).

UPDATE: Some people have responded with ways that may work in one-off statements, I need a way to put this into an UPDATE statement.

For example: UPDATE MyTable SET MyField = MyFunction(MyField)

Where MyFunction is the correct answer to this question.


回答1:


this will give you what you want..8534788b-9000-4729-846b-81a3f49c9f91

select CONVERT(varchar(36),
0x38353334373838622D393030302D343732392D383436622D383161336634396339663931)

you need to convert the value to varbinary and then convert back to varchar

here is one way using dynamic SQL

    declare @v varchar(100)
 select @v = '0x' + '38353334373838622D393030302D343732392D383436622D383161336634396339663931'

exec ( 'SELECT CONVERT(varchar(36),' + @v + ')')



回答2:


If you want to convert individual characters you can do it with the CHAR function as:

SELECT CHAR(0x38)

But you have to remember to prefix the number with 0x since it's hexadecimal.



来源:https://stackoverflow.com/questions/2907939/hex-characters-in-varchar-is-actually-ascii-need-to-decode-it

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