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 field with count

Author  Topic 

Vack
Aged Yak Warrior

530 Posts

Posted - 2009-05-27 : 09:19:25
I want to count records in one table(orderrebatehistory) and update another table(orhrecordcount) with the count.

I've tried this but the update is not working.

update orhrecordcount
set recordcount = (select count(*) from orderrebatehistory)

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-05-27 : 09:23:36

You may need something like this

update t1
set recordcount = (select count(*) from orderrebatehistory where keycol=t1.keycol)
from orhrecordcount as t1


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-05-27 : 09:25:36
or

update t1
set recordcount = t2.count
from orhrecordcount as t1 inner join
(
select keycol,count(*) as count from orderrebatehistory
group by keycol
) as t2
on keycol=t1.keycol


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

Vack
Aged Yak Warrior

530 Posts

Posted - 2009-05-27 : 09:26:36
I do not have a key in my orhrecordcount table. I was just using it as a place to store the count. One record one field.
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2009-05-27 : 09:31:27
What was wrong with your query?
Did you get error?

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2009-05-27 : 09:31:33
quote:
Originally posted by Vack

I do not have a key in my orhrecordcount table. I was just using it as a place to store the count. One record one field.



is it for temporary storage ? Why use a table ? an integer variable will be able to do that

declare @cnt int

select @cnt = count(*)
from orderrebatehistory



KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

Vack
Aged Yak Warrior

530 Posts

Posted - 2009-05-27 : 09:33:03
I added a key column to the orhrecordcount and that seemed to have solved my problem.

Thanks
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-05-27 : 09:42:38
quote:
Originally posted by Vack

I added a key column to the orhrecordcount and that seemed to have solved my problem.

Thanks


why use a table just to store a count value?
Go to Top of Page
   

- Advertisement -