views:

187

answers:

2

With a temporary table as:

DECLARE @Results TABLE (
    CDA  varchar(60),
    Found  int default 0,
    Accepted int default 0,
    Percentage decimal(3,0) default 0.0,
)

How do you take populated Found and Accepted columns and write it back to the Pecentage column?

I have:

UPDATE @Results SET Percentage = (
    SELECT (((Accepted * 1.00) / Found) * 100) FROM @Results 
)

Which if you take the SELECT line (comment out the UPDATE) it returns the correct values. However in the context of the UPDATE it fails with Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression. The statement has been terminated.

How do I write the values back to the correct row?

+1  A: 

You need a where clause, e.g. (untested)

UPDATE Result oResult
  SET Percentage = (SELECT Accepted / Found * 100
                      FROM Result iResult 
                     WHERE iResult.cda = oResult.cda);

However, if this is calculated you may wish not to have this as a column and just add it to any queries instead. Note, most databases have a percent function.

vickirk
I thought about the query but why complicate the query (this will becomea stored procedure) when I can hide the complexity here?
graham.reeds
It gives Invalid Syntax for oResult. Tried both equals and AS and neither works.
graham.reeds
What database are you using? Works on oracle here. > but why complicate the query (this will becomea stored procedure) when I can hide the complexity here?Because you know the data will be correct and you are not relying on your procedure having been called each time you update a value.
vickirk
Appears you are not allowed to Alias Tables in update statements.
graham.reeds
SQL Server 2000.
graham.reeds
Sorry, don't have access to a SQL Server and never used it. The following works on mysql UPDATE Result oResult LEFT JOIN (SELECT Accepted / Found * 100 AS pc, cda FROM Result) as iResult on iResult.cda = oResult.cda SET oResult.Percentage = iResult.pc;
vickirk
Looking at that it won't work because MS-SQL Server doesn't allow aliasing of tables in update statements.
graham.reeds
Sorry I can't help with sql server, try googling for correlated subqueries with ms sql server, a few possible solutions turned up but i can't try them
vickirk
+1  A: 
UPDATE Result
   SET Percentage = Accepted / Found * 100

It won't work though with FOUND and ACCEPTED defined as INT, use cast when dividing or declare them with the same type as PERCENTAGE.

Joel
I can't believe it was that simple! However it is a moot point as I ended up calculating the percentage in reporting services via an expression.
graham.reeds