简体   繁体   中英

SQL Server 2008 R2: How to identify and update hexadecimal value

I have the following table called as Hexa_Table which consists of only one column namely val .

Table : Hexa_Table

CREATE TABLE Hexa_Table
(
 val VARCHAR(50)
);

Insertion :

INSERT INTO Hexa_Table VALUES('123456789101213');
INSERT INTO Hexa_Table VALUES('414F2D53594F545641');
INSERT INTO Hexa_Table VALUES('1234F6789A1213G');
INSERT INTO Hexa_Table VALUES('414F2D363530303035');
INSERT INTO Hexa_Table VALUES('12345678910');

Note : Now I want to update only those values which are Hexadecimal and want to update it to String , for which I need to identify which are the Hexadecimal values in the table.

For example I have record number 2 that is 414F2D53594F545641 if you convert it will get AO-SYOTVA . And in 4th record I have 414F2D363530303035 if you convert it will get AO-650005 .

Converted by using : This

Questions :
1. How to identify hexadecimal values in the table?
2. How to update hexadecimal values to string?

You can use CONVERT with style 1 . Something like this in your scenario.

You can use Filter NOT LIKE '%[^0-9a-f]%' to match exact hex pattern and LEN(val) %2 = 0 to check if it has exact number of required bytes for convert

SELECT  val,
    CAST(CONVERT(varbinary(4), '0x' + val, 1) As VARCHAR(100)) as charstring,
    CONVERT(varbinary(4), '0x' + val, 1) as HexVal
FROM Hexa_Table
WHERE val NOT LIKE '%[^0-9a-f]%'
AND LEN(val) %2 = 0;

Output:

val charstring  HexVal
414F2D53594F545641  AO-S    0x414F2D53
414F2D363530303035  AO-6    0x414F2D36

Reference

How can I convert a varchar with hexadecimal value to int?

MSDN Convert

You can find hexadecimal values in your table using this:

like '%' + CHAR(0x00) +'%'

However in your example which you have shown, the values are stored already as string so I am not sure what you mean to convert the values as string.

On a side note:

If you want to know how to convert the hex to varchar then you need to use CONVERT like this":

CONVERT(VARCHAR(MAX), 0x48656c70)

To find out hexadecimal values you can in following:

select val
from Hexa_Table
where val like '%' + CHAR(0x00) +'%'

It is already stored as VARCHAR , what and how do you want to update?

Try this code:

BEGIN TRAN

SELECT * FROM Hexa_Table 
WHERE val = @value_insert

IF (@@ROWCOUNT = 0)
    INSERT Hexa_Table
    SELECT CONVERT(VARCHAR(50), @value_insert)

COMMIT

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM