0

I need to perform an update in a table that is a result of a dynamic pivot. So number of columns and column names are dynamic. Really puzzles me how to do it, as I might need nested dynamic SQL which I cannot find out how to get it work.

So far I found out how to create a table with all update queries, but I cannot find out how to run the queries from the table. The query to create a table with all update queries is:

SELECT 
N'UPDATE #Pivot SET [' + t1.a + '] = ''' + t2.b  + ''' WHERE #Pivot.y = ''' + t1.x + '''' AS Query
FROM t1
INNER JOIN t2 
    on t2.v = t1.v

The column headers in the pivot originate from t1.a, therefore I use t1.a to retrieve the column headers. Pivot.y is the non-pivoted column of the pivot and also originates from t1.

Maybe this is not the easiest way and someone knows a better way? Maybe it's easy, but I'm very new to dynamic queries. Thanks in advance for helping!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Cewher
  • 1
  • http://stackoverflow.com/questions/12430512/dynamic-pivot-table-in-sql-server – EarlOfEnnui Apr 08 '16 at 12:12
  • Can you update the table before doing the pivot, so you wouldn't need to do it dynamically? Or include the logic of the update in the Pivot so that it is already done when you pivot? – Tab Alleman Apr 08 '16 at 13:32
  • I cannot unfortunately, as the values I want to insert are varchar values and they cannot be pivoted. – Cewher Apr 08 '16 at 14:48

0 Answers0