"Rodusa" <rc**********@yahoo.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
Thanks, Simon, I just changed it a little bit. I am almost there.
There is just one piece which is not working.
On the piece below I am trying to substitute "SELECT sum(total_amount)
AS total FROM testdb.dbo.invoice_hdr" with @sql but I am getting an
error:
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near '@sql'.
Server: Msg 16950, Level 16, State 2, Line 17
The variable '@my_cur' does not currently have a cursor allocated to
it.
<snip>
I don't really understand your code - why is this line inside the cursor
loop?
update Sn_SalesReport set dollar_amount = @total
The value of dollar_amount will change every time you go through the loop,
and without a WHERE clause, every row will change (unless it's a one-row
table, of course). As a complete guess, you want something like this:
declare @sql nvarchar(512),
@total decimal(19,4),
@grand_total decimal(19,4)
set @grand_total = 0.0
DECLARE my_cursor CURSOR FOR
SELECT sqlstatement from Sn_SalesReport
OPEN my_cursor
FETCH NEXT FROM my_cursor INTO @sql
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC sp_executesql @sql, N'@total decimal(19,4) OUTPUT', @total OUTPUT
set @grand_total = @grand_total + isnull(@total, 0.0)
FETCH NEXT FROM my_cursor INTO @sql
END
CLOSE my_cursor
DEALLOCATE my_cursor
update dbo.Sn_SalesReport
set dollar_amount = @grand_total
-- where ... ??
Here, you need @sql to look like this, to match the @total output parameter:
'select @total = sum(total_amount) from testdb.dbo.invoice_hdr'
I would also suggest - as David did - that there may be easier ways to
produce reports than writing your own reporting tool (which seems to be more
or less what you're doing). Nested cursors with dynamic SQL and user-defined
SQL statements create a number of fairly significant maintenance and
security issues. Going for a proper reporting tool will save you a lot of
time of effort in the longer run, although I appreciate that in the short
term any new solution will have a learning curve. SQL Server Reporting
Services is free if you have an MSSQL licence, for example:
http://www.microsoft.com/sql/reporting/default.asp
Simon