Wednesday, 22 April 2009

Show hex values of characters in an SQL Server field

-- The @position variable holds the position of the character currently
-- being processed. The @nstring variable is the Unicode character
-- string to process.
DECLARE @position int, @nstring nvarchar(max)
-- Initialize the current position variable to the first character in
-- the string.
SET @position = 1
-- Initialize the character string variable to the string to process.
-- Notice that there is an N before the start of the string, which
-- indicates that the data following the N is Unicode data.
SELECT @nstring = colname FROM table WHERE criterion_col = value
-- Print the character number of the position of the string you are at,
-- the actual Unicode character you are processing, and the UNICODE
-- value for this particular character.
PRINT 'Character #' + ' ' + 'Unicode Character' + ' ' + 'UNICODE Value'
WHILE @position <= DATALENGTH(@nstring)
-- While these are still characters in the character string,
BEGIN
SELECT @position AS pos,
CONVERT(char(17), SUBSTRING(@nstring, @position, 1)) AS [Unicode char],UNICODE(SUBSTRING(@nstring, @position, 1)) AS val
SELECT @position = @position + 1
END