• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 231
  • Last Modified:

Dynamic SQL

I have 10 columns on a GUI interface the user can group by or sum by any of these 10 columns.

There are two listboxes one for group by and one for sum by.

The user can choose the columns to group by and also the columns to sum by.

I need to write a dynamic sql query to fetch the data based on the columns selected for grouping and sum.
Any examples would be great
0
countrymeister
Asked:
countrymeister
1 Solution
 
Shaun KlineLead Software EngineerCommented:
If you have a GUI interface, can you build the SQL there and send it to SQL Server?

Are you displaying those same 10 columns or are there other columns that are displaying?
0
 
PortletPaulfreelancerCommented:
Can you explain what the "sum by" is intended to do?
Do you have some "roll-up" capability in mind so that you achieve sub-totals and grand totals?
0
 
SharathData EngineerCommented:
Pass the two columns from GUI interface to your database and you can construct a dynamic sql and execute.
You can create an SP and pass the parameters. check this code if this works for you.
DECLARE @GroupBy VARCHAR(100),@SumBy VARCHAR(100)
DECLARE @Sql VARCHAR(MAX)
SELECT @Sql = 'SELECT ' + @GroupBy + ',SUM(' + @SumBy + ') AS SumBy
                 FROM YourTable
				GROUP BY ' + @GroupBy
EXEC(@Sql)

Open in new window

0
 
countrymeisterAuthor Commented:
I would suggest not to use exec @sql , instead use Execute sp_Executesql
Where we can send parameters, also the query plan is cached
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now