I would like $1000.00 to go to the Flying A column and $500.00 go to the flying B column for the matching Mission #.
NOTE: Mission #s in Table1 are not unique; therefore, salaries for records with the same Mission # will be need to be summed in a temporary table before moving to Table2 (unless you have a better approach).
Thus Far I have the following code(using a temporary table to sum by Mission#):
DECLARE @ID INT DECLARE @Mission# NVARCHAR(100) DECLARE @Category NVARCHAR(100) DECLARE @Category2 NVARCHAR(100) DECLARE @Salary MONEY DECLARE @ColumnName NVARCHAR(1000) SET @ID = 1 --While @ID < 167921 --Begin SET @Mission# = (SELECT mission# FROM temporarytable WHERE id = @ID) SET @Category = (SELECT category FROM temporarytable WHERE id = @ID) SET @Category2 = (SELECT category2 FROM temporarytable WHERE id = @ID) SET @Salary = (SELECT salary FROM temporarytable WHERE id = @ID) SET @ColumnName = 'Base Salaries for ' + @Category + ' - ' + @Category2 EXECUTE ('update Table2 set @ColumnName = ''' + @Salary + ''' where [Mission#] = ''' + @Mission# + '''') --Set @ID = @ID + 1 --End
However, I can't seem to get the @ColumnName variable into the execute statement unless is is hard coded as the actual column name (eg. "Salaries for flying A - aircraft"). When I try and use @ColumnName I get a "must declare scalar variable "@ColumnName" error. If I mess around with the syntax a bit and use
Thanks Daniel, the Dynamic SQL syntax is pretty confusing. Both your methods work wonderfully.
Do any tips on speeding up this loop? I'm running SQL server locally on my laptop and this executes at a speed of about .17 seconds per record and will take about 8 Hours to complete..? Most of the time is being spent on Index Seek and RID Lookup (Heat).
If I understand correctly, you don't need a temp table.
INSERT INTO table2 ( mission#, [Salaries for flying A - aircraft], [Salaries for flying B - aircraft] )
SELECT mission#,
SUM(CASE WHEN category = 'flying A' /*AND category2 = 'aircraft'*/ THEN salary ELSE 0 END) AS [Salaries for flying A - aircraft],
SUM(CASE WHEN category = 'flying B' /*AND category2 = 'aircraft'*/ THEN salary ELSE 0 END) AS [Salaries for flying B - aircraft]
FROM table1
WHERE
category IN ('flying A', 'flying B') /*AND category2 = 'aircraft'*/
GROUP BY mission#
-Polak
ASKER
@Scott, if i understand you correctly. Yes, transposing the data would likely run quicker; however, what's not completely clear in my example (my fault) is that Table2 already has mission # data in it and what needs to be brought over from Table1 is the salary information depending on category and category2.
Not sure I can help with the speed issue. A couple things that might help, This:
SET @Mission# = (SELECT mission# FROM temporarytable WHERE id = @ID) SET @Category = (SELECT category FROM temporarytable WHERE id = @ID) SET @Category2 = (SELECT category2 FROM temporarytable WHERE id = @ID) SET @Salary = (SELECT salary FROM temporarytable WHERE id = @ID)
Open in new window