How to convert varchar with hex value to int?

I need to convert VARCHARwith a hexadecimal number in INT, I tried:

DECLARE @H VARCHAR(2);
SELECT @H = '9a'
SELECT CONVERT(INT, 0x + @H)

But he says it @Hshould be VARBINARY, and if I surrender, I get a completely different number.

From '9a'I want to get 154, how can I achieve it?

+3
source share
3 answers

If in 2008 you can use

Select @Value = Cast(CONVERT(varbinary(4), '0x' + @HexValue, 1) As int)
+3
source

It looks like this guy will get you into varbinary, then you can just use the CONVERT function.

It looks like you can do this natively with XML. WTF Micsrosft XML?

+1
source
Declare @HexValue varchar(10)
Set @HexValue = '9a'

Declare @Sql nvarchar(max)
Declare @Value int

Set @Sql = 'Select @Value = Cast(Cast(0x' + @HexValue + ' as varbinary(4)) As int)'
exec sp_executesql @Sql, N'@Value int OUTPUT', @Value OUTPUT

Select @Value
+1

Source: https://habr.com/ru/post/1761997/


All Articles