2017-08-17 87 views
2

這裏是我的十六進制輸入如何十六進制轉換爲字符串在SQL Server

0x3c0x3c0x5bIMG0x5d0x5bSIZE0x5dHALF0x5b0x2fSIZE0x5d0x5bID0x5d540x5b0x2fID0x5d0x5b0x2fIMG0x5d0x3e0x3e 

預期成果是:

<<[IMG][SIZE]HALF[/SIZE][ID]54[/ID][/IMG]>> 
+0

https://dba.stackexchange.com/questions/132996/convert-hexadecimal-to-varchar –

+0

SELECT CONVERT(VARCHAR(MAX),0x3c0x3c0x5bIMG0x5d0x5bSIZE0x5dHALF0x5b0x2fSIZE0x5d0x5bID0x5d540x5b0x2fID0x5d0x5b0x2fIMG0x5d0x3e0x3e); –

+0

此鏈接doenst幫助我。需要得到確切的結果<< [IMG] [SIZE] HALF [/ SIZE] [ID] 54 [/ ID] [/ IMG] >>這個結果。 –

回答

1

如果它是隻有一小集,總是需要更換一個變量,那麼你也可以替換他們這樣的ASCII碼:

declare @string varchar(max) = '0x3c0x3c0x5bIMG0x5d0x5bSIZE0x5dHALF0x5b0x2fSIZE0x5d0x5bID0x5d540x5b0x2fID0x5d0x5b0x2fIMG0x5d0x3e0x3e'; 

select @string = replace(@string,hex,chr) 
from (values 
('0x3c','<'), 
('0x3e','>'), 
('0x5b','['), 
('0x5d',']'), 
('0x2f','/') 
) hexes(hex,chr); 

select @string as string; 

返回:

string 
------ 
<<[IMG][SIZE]HALF[/SIZE][ID]54[/ID][/IMG]>> 

如果有更多的字符,或者硬編碼被壓低了?
然後循環的替代也將得到這一結果:

declare @string varchar(max) = '0x3c0x3c0x5bIMG0x5d0x5bSIZE0x5dHALF0x5b0x2fSIZE0x5d0x5bID0x5d540x5b0x2fID0x5d0x5b0x2fIMG0x5d0x3e0x3e'; 

declare @loopcount int = 0; 
declare @hex char(4); 
while (patindex('%0x[0-9][a-f0-9]%',@string)>0 
     and @loopcount < 128) -- just safety measure to avoid infinit loop 
begin 
    set @hex = substring(@string,patindex('%0x[0-9][a-f0-9]%',@string),4); 
    set @string = replace(@string, @hex, convert(char(1),convert(binary(2), @hex, 1))); 
    set @loopcount = @loopcount + 1; 
end; 

select @string as string; 

如果你想在一個UDF包,那麼你甚至可以在查詢中使用它。

+0

這是我正在尋找的,真的很感謝你的幫助! –

+0

@NileshBankar謝謝。如果有更多的代碼需要替換,我已經包含了非硬編碼版本。 – LukStorms

2

你的字符串是混合十六進制和字符的數據,所以你需要對它進行解析用代碼。一個棘手的部分是將0xCC子字符串轉換爲它表示的字符。首先假設它是二進制的,然後轉換爲char。使用遞歸所有0xCC子迭代

declare @imp nvarchar(max) = '0x3c0x3c0x5bIMG0x5d0x5bSIZE0x5dHALF0x5b0x2fSIZE0x5d0x5bID0x5d540x5b0x2fID0x5d0x5b0x2fIMG0x5d0x3e0x3e'; 

with cte as (
select replace(col, val, cast(convert(binary(2), val, 1) as char(1))) as col 
from (
    -- sample table 
    select @imp as col 
    ) tbl 
cross apply (select patindex('%0x__%',tbl.col) pos) p 
cross apply (select substring(col,pos,4) val) v 
union all 
select replace(col, val, cast(convert(binary(2), val, 1) as char(1))) as col 
from cte 
cross apply (select patindex('%0x__%',col) pos) p 
cross apply (select substring(col,pos,4) val) v 
where pos > 0 
) 
select * 
from cte 
where patindex('%0x__%',col) = 0; 

返回

col 
<<[IMG][SIZE]HALF[/SIZE][ID]54[/ID][/IMG]>> 
+0

感謝您的幫助! –

相關問題