• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 224
  • 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
 
PortletPaulCommented:
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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

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