Georged Weblog

Have you georged your mind?

"Static" variables in SQL

I did not realise that declared variables in SQL are effectively “static” when used in rowsets. That is, the following code:

create table roles(role nvarchar(50))
GO
insert roles
select 'Administrator' union
select 'Editor' union
select 'User'
go

declare @roles nvarchar(1024)
select @roles = isnull(@roles + ', ', '') + role from roles
select @roles
go

drop table roles
go

yeilds “Administrator, Editor, User“.

Wow! Now instead of returning rowset of roles for a user and then concatenating results in client-side code, I can just write a function similar to:

create function fnGetUserRoleVerbose(@userid int, @delim nvarchar(2) = ', ')
returns nvarchar(1024)
as
begin
   declare @role nvarchar(1024)
  
   select
      @role = isnull(@role + @delim, '') + roles.name 
   from
      users
      inner join users_roles
         on users.id = userid
      inner join roles
         on roleid = roles.id
   where
      users.id = @userid
 
   return @role
end

and then just do this:

string roles = (string) SqlHelper.ExecuteScalar(
    myConnectionString, 
    CommandType.Text,
    string.Format("select dbo.fnGetUserRoleVerbose({0}, default)", userId));

 

Posted: Oct 16 2003, 11:29 PM by georged | with 6 comment(s)
Filed under:

Comments

Darren Neimke said:

I don't mean to sound negative against this idea - because I'm not, but... you've effectively moved a piece of code from one tier to another and for what? Have you reduced the overall lines of code required?
# October 16, 2003 9:46 AM

Denny said:

I think Darren may be missing the point....
(or I am ? )

some of the dotnet security api's want you to give them a user and a list of roles...

so while we tend to store them as:
1 arole1
2 arole2
3 arole3

the api wants
"arole1,arole2,arole3"

and who wants to have to pull n rows from the server and then have to format them?
not me if the server can give me a one shot reply....
datareader loop code vs executescaler()
I'll take the scaler !

# October 16, 2003 1:16 PM

George Doubinski said:

Darren,
by the same logic middle-tiers are hardly ever worth the effort because number of lines of code is usually increased by introducing new tiers.
But to answer your question: I indeed reduced number of lines of code required, but most importantly, I reduced network traffic between IIS and SQL, I improved overall performance and I moved code to SQL, where we tend to have better skills and resources (your mileage may vary).
OTOH, this is was just the sample to illustrate how T-SQL treats variables in rowsets.
# October 16, 2003 7:12 PM

robert said:

That IS exceedingly cool! I just replaced a verbose UDF that used a loop with your much more elegant solution.
# October 17, 2003 1:16 AM

TrackBack said:

^_^,Pretty Good!
# April 9, 2005 1:00 PM

- SQL Treeo said:

Pingback from  - SQL Treeo

# June 5, 2011 8:40 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)