1

My SQL is very rusty. Am trying to update a counter in a row in a table with a COUNT(*) from that same table in the form of a nested query. The SQL is below:

UPDATE DWInvoiceHeader AS A
SET A.InvCount = (Select Count(B.HIINV) From DWInvoiceHeader AS B 
                  WHERE (B.HIVENT = '0') 
                  Group By B.HIINV 
                  Order By B.HIINV)
WHERE (A.HIVENT = '0');

The rows look like:

HIINV1.......Seq1.....InvCount   - want InvCount to be 3
HIINV1.......Seq2.....InvCount   - want InvCount to be 3
HIINV1.......Seq3.....InvCount   - want InvCount to be 3
HIINV2.......Seq1.....InvCount   - want InvCount to be 2 
HIINV2.......Seq2.....Invcount   - want InvCount to be 2
.
.
.
HIINVn.......Seq1.....InvCount   - want InvCount to be 1

The SQL above gives me the message "Operation must be an updateable query".

Any ideas ?

1

2 Answers 2

0
UPDATE DWInvoiceHeader AS A
SET A.InvCount = 
(
    Select Count(B.HIINV) 
        From DWInvoiceHeader AS B 
        WHERE (B.HIVENT = '0') AND (A.HIINV = B.HIINV)
        Group By B.HIINV 
)
WHERE (A.HIVENT = '0');
Sign up to request clarification or add additional context in comments.

1 Comment

@RawleRamkeesoon, Wasn't it a nested query you have requested? dose the above solution give the desired result set? has the above solution caused an error?
0

You could use the Domain Function Dcount in a way similar to:

UPDATE test
SET InvCount = Dcount("HIVENT","test","[HIVENT]='0'")

If you want to use a generic approach then I would suggest to store the counts in a working table and then update your table joining the working table.

    Select B.HIINV,Count(B.HIINV) as InvCount 
    into WorkingTbl
    From DWInvoiceHeader AS B 
    WHERE (B.HIVENT = '0') AND (A.HIINV = B.HIINV)
    Group By B.HIINV 

   Update   DWInvoiceHeader  A 
   Inner Join WorkingTbl b 
   on a.HIINV=b.HIINV 
   Set A.InvCount=b.InvCount

4 Comments

Tried this 2-part solution involving an intermediate table and it worked fine. The DCOUNT function code gave a "Missing operator" message.
Dcount should be like this: Dcount("HIINV" ,"DWInvoiceHeader", "(B.HIVENT = '0') AND (A.HIINV = B.HIINV)")
But In general: Office support on Dcount function tip: The Count function has been optimized to speed counting of records in queries. Use the Count function in a query expression instead of the DCount function, and set optional criteria to enforce any restrictions on the results. Use the DCount function when you must count records in a domain from within a code module or macro, or in a calculated control.
try the edited Dcount function again and see if it works please

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.