I think this a interesting question and pretty much buried in the original thread. It's posted by yelworcm:
Code:
What function returns 0, if called first thing after connecting to SQL Server, but never returns 0 after that initial call.
I can think of a way using procedure to achieve it, better let someone else change it to a UDF, following is my procedure
Code:
CREATE procedure getst
@cnt int output
AS
BEGIN
set nocount on
if not exists(select * from tempdb..sysobjects where name like '##ses%')
create table ##ses(ses_id binary(128), cnt int)
declare @ses_id as binary(128)
set @ses_id = ( select context_info from sysprocesses where spid = @@spid)
update ##ses set cnt = cnt + 1
where ses_id = @ses_id
if (@@rowcount = 0)
insert into ##ses values(@ses_id, 0 )
select @cnt = cnt from ##ses
set nocount off
END
to test it:
Code:
declare @test int
exec getst @test output
select @test