0

Good Afternoon All,

Can anyone advise if I can dynamically declare and assign values to variables in the scenario described below?

I've written a stored procedure (sproc) that calculates the % of members in subgroups of an organization.

I know there are 7 subgroups. I store the results of the percentage calculation in 7 variables which I use later in the sproc. Each variable is named according to the subgroup name.

Naturally this means if there are changes in the name or number of subgroups, I have to rewrite parts of the sproc.

I believe dynamic SQL could be used to allow the sproc to adjust to changes in the subgroups, but I'm not sure how to set up dynamic SQL for this scenario. Can anyone offer an example or guidance?

1
  • 1
    Dynamic SQL is usually not the solution to sql problems. Like cursors, it has its place, but its easy to screw up, difficult to maintain, and vulnerable to injection attacks. Consider using a temp table (or table variable) that has a row for each "variable" instead of using standard sql variables. Commented Apr 22, 2016 at 16:20

2 Answers 2

1

What you're proposing goes against the grain in Sql Server. Your concern about having to rewrite later kinda speaks to this...so you're on the right track to be concerned.

Generally, you'd want to make your results into some kind of set-oriented thing...table-like...where one column has the name of the subgroup and the other column has the calculated value.

You might find table-valued functions more appropriate for your problem...but it's hard to say...we're not deep on specifics in this question.

Dynamic SQL is almost always the last resort. It seems fun, but has all sorts of issues...not the least of which is addressing the results in a programmatically safe and consistent way.

Sign up to request clarification or add additional context in comments.

Comments

0

You can follow this simple query to see how you can do that

declare @sql nvarchar(max) = ''
declare @outerX int = 0 -- this is your variable you want to set it from dynamic SQL 
declare @i int = 0 -- for loop

while @i <= 6 
begin
  set @sql = 'select @x = ' + CAST(@i as varchar)
  exec sp_executesql @sql, N'@x int OUTPUT', @x = @outerX output
  set @i = @i + 1
  print @outerX
end

Output will be

0
1
2
3
4
5
6

More Detail Here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.