Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting CONTEXT_INFO to varchar and the resulting length

I'm trying to use CONTEXT_INFO to pass a usercode from a stored procedure into a DELETE trigger for table auditing purposes.

It all works fine, however I noticed that the length of the usercode saved in the audit table was not correct.

Take this script as an example...

declare @userCode varchar(50)
set @userCode = 'TestUser'

declare @binary_userCode varbinary(128)
set @binary_userCode = cast(@userCode as varbinary(128))
set CONTEXT_INFO @binary_userCode

declare @temp_userCode varchar(50)
set @temp_userCode = (select cast(CONTEXT_INFO() as varchar(50)))

--set @temp_userCode = rtrim(ltrim(@temp_userCode))

select @userCode, len(@userCode), @temp_userCode, len(@temp_userCode)

set CONTEXT_INFO 0x

Results:

len(@userCode) = 8

len(@temp_userCode) = 50

Why is the @temp_userCode variable coming back with a length of 50, and how can I trim it back to it's original length to store it correctly?

Further Information:

Running SQL Server 2005, however the solution needs to work in all versions 2005 onwards.

like image 965
Brett Postin Avatar asked Feb 24 '12 16:02

Brett Postin


Video Answer


2 Answers

When assigned to CONTEXT_INFO it gets padded out with null bytes 0x00 to 128 bytes in length and becomes 0x5465737455736572000000...

You can use

REPLACE(CAST(CONTEXT_INFO() AS varchar(128)) COLLATE Latin1_General_100_BIN , 
        0x00, 
        '')
like image 80
Martin Smith Avatar answered Oct 20 '22 18:10

Martin Smith


It gets padded with CHAR(0). Try:

set @temp_userCode = REPLACE(@temp_userCode COLLATE Latin1_General_BIN, CHAR(0), '');

(EDIT: added an explicit COLLATE clause, though now I feel like I'm stealing from Martin.)

like image 32
Aaron Bertrand Avatar answered Oct 20 '22 20:10

Aaron Bertrand