Solved

Dynamic SQL

Posted on 2014-01-09
4
206 Views
Last Modified: 2014-01-17
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
Comment
Question by:countrymeister
4 Comments
 
LVL 25

Expert Comment

by:Shaun Kline
Comment Utility
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
 
LVL 48

Expert Comment

by:PortletPaul
Comment Utility
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
 
LVL 40

Accepted Solution

by:
Sharath earned 500 total points
Comment Utility
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
 
LVL 1

Author Closing Comment

by:countrymeister
Comment Utility
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Naughty Me. While I was changing the database name from DB1 to DB_PROD1 (yep it's not real database name ^v^), I changed the database name and notified my application fellows that I did it. They turn on the application, and everything is working. A …
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video discusses moving either the default database or any database to a new volume.
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now