Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Values as column names

$
0
0

It's a little difficult to explain but here goes nothing...

I am dynamically generating SQL and executing using sp_ExecuteSql.  When the query is built it comes from values in a configuration table and just gets a record count.  There are common fields for each database, and also some that are not common so they're stored in "GroupByField1", etc.  So consider this configuration record.

DBName | WeightField | ColorField | GroupByField1 | GroupByField2 | GroupByField1Description | GroupByField2Description

FirstDB | ItemWeight | ItemColor | ItemType | NULL | Item Type | NULL

AnotherDB | ItemWt | ItemClr | NULL | NULL | NULL | NULL

In the first database the weight is called ItemWeight, in the second it's called ItemWt.  The first database also has a ItemType field that I want to group by, and it will be labeled "Item Type".

So the SQL that is generated would be something like:

INSERT INTO ResultTable (ItemWeightValue, ItemColorValue, GroupByField1, RecordCount) SELECT ItemWeight, ItemColor, ItemType, COUNT(1) FROM FirstDB.dbo.StandardTableName GROUP BY ItemWeight, ItemColor, ItemType

INSERT INTO ResultTable (ItemWeightValue, ItemColorValue, RecordCount) SELECT ItemWt, ItemClr, COUNT(1) FROM FirstDB.dbo.StandardTableName GROUP BY ItemWt, ItemClr


Running the SQL is no problem, it's generating valid queries just fine and inserts the results I expect.

What I'm looking for is a way to return a different result based on the DBName.  I'm no good with PIVOT, CROSS JOIN, CROSS APPLY, etc and I'm not sure if those would be of any use or not.  Basically the results for the two records above would be:

DBName | ItemWeight | ItemColor | "Item Type" | RecordCount

DBName | ItemWeight | ItemColor | RecordCount

Outside of a SP to return all of this can anyone think of a simple way to use a related column value (ie - "Item Type") as the column name in a query?

Thank you!



Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>