Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 UPDATE query help

Author  Topic 

Apples
Posting Yak Master

146 Posts

Posted - 2008-10-17 : 17:43:29
Here's my schema and data:

------------------------------------------------
tblEntries
------------------------------------------------
EntryID | CommentCount
------------------------------------------------
1 | 0
2 | 0
------------------------------------------------

------------------------------------------------
tblComments
------------------------------------------------
CommentID | EntryID
------------------------------------------------
1 | 1
2 | 1
3 | 2
------------------------------------------------

I want to update the CommentCount for entries in tblEntries by passing in the CommentID's.

Here is my query:

UPDATE tblEntries
SET CommentCount = CommentCount + 1
WHERE EntryID IN (
SELECT EntryID
FROM tblComments
WHERE CommentID IN (1,2,3))

The subquery returns:
1
1
2

But when it goes to update the entries, Entry 1 only gets the CommentCount updated to 1 instead of 2. I assume it is because the 'WHERE EntryID IN (' clause doesn't deal with duplicates?

raky
Aged Yak Warrior

767 Posts

Posted - 2008-10-18 : 01:17:19
Try this

DECLARE @temp TABLE ( cnt INT, entryid int)
INSERT INTO @temp
SELECT COUNT(CommentID), entryid
FROM tblComments
GROUP BY entryid

UPDATE te
SET CommentCount = CommentCount + cnt
FROM tblEntries te
inner join @temp tc on ( tc.entryid = te.entryid)

SELECT * FROM tblEntries
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-10-18 : 01:54:36
or simply without using temp table
UPDATE t
SET t.CommentCount=t.CommentCount+c.cnt
FROM tblEntries t
INNER JOIN (SELECT COUNT(CommentID) AS cnt,EntryID
FROM tblComments
GROUP BY EntryID)c
ON c.EntryID=t.EntryID
Go to Top of Page
   

- Advertisement -