tags:

views:

18

answers:

1

What can I do wtih a binary data type in SQL Server to make my life easier?

I recently found out about this nifty feature

DECLARE @p0 varbinary(128)
SET @p0 = --?
SET CONTEXT_INFO @p0

How can I in a reasonable efficient manner store data that makes some sense in this binary slot? Oh, and then access that data in some reasonable way?

SELECT ? = context_info
FROM sys.dm_exec_sessions
WHERE session_id = @@SPID

Update: as pointed out by gbn

SELECT ? = CONTEXT_INFO()

A more useful approach would be to rely on CONTEXT_INFO() to return a Row ID of some context table. Say:

SELECT * 
FROM ContextTable 
WHERE RowID = CONTEXT_INFO()

That would allow me to query context information.

+1  A: 

It's useful for passing data into a trigger, say, the username from your web site into a audit trigger.

I'd also use CONTEXT_INFO() to read the data back out (for SQL Server 2005 and higher)

One gotcha: it starts NULL but you can not assign NULL back to it after use. You have to use 0x00.

gbn
Yes, that's what I aim to do, but the binary isn't really a useful type to work with, now is it?You could use the @@SPID to maintain a table with state, (that row you can query and that's practical).Btw, do you know if the CONTEXT_INFO() starts out NULL for each session, becuase that would make sense?Thanks for the CONTEXT_INFO(), didn't know about that one either. This is great stuff.
John Leidegren
yes, starts at NULL but can't be reset back. I use it for triggers only.
gbn