0

So I've found myself with a need to have a field in my table that is a count of all the 'Shops' in another table. The table should therefore consist of Centre_Name, Location and Shop_Count. I've already created the table, so how do I add such a field?

The field should also obviously update when a shop is added or deleted in the other table. Also, each shop has a corresponding Centre_Name.

The table is in a SQL Server Express database, linked to my MVC 4 project in Visual Studio.

Thanks!

barnacle.m
  • 2,070
  • 3
  • 38
  • 82

1 Answers1

2

It's pretty heavy denormalization, but you could make a function to get the count and then use that function as part of a computed column. See: define a computed column reference another table

So you'd want to do:

CREATE FUNCTION dbo.CountShops (@Centre_Name VARCHAR[x])
RETURNS INT 
AS BEGIN
    DECLARE @ShopCount INT

    SELECT @ShopCount = COUNT(*) FROM dbo.Shops WHERE Centre_Name = @Centre_Name

    RETURN @ShopCount
END

And then call that as part of your column:

ALTER TABLE dbo.Shops
ADD Shop_Count AS dbo.CountShops(Centre_Name) 

...this is assuming Centre_Name is the defining attribute of what you're counting shops by. What are you counting shops by? If it's just counting rows in the shops table, you could drop the parameter and do:

CREATE FUNCTION dbo.CountShops ()
    RETURNS INT 
    AS BEGIN
        DECLARE @ShopCount INT

        SELECT @ShopCount = COUNT(*) FROM dbo.Shops

        RETURN @ShopCount
    END

More on computed columns here.

Community
  • 1
  • 1
antinescience
  • 2,339
  • 23
  • 31
  • I figured there was something really bad about doing this, but I need the centre_name and shop_count together, to create an html combobox with the names in the list and each name with the shop count as the assigned value. – barnacle.m Mar 24 '13 at 21:23
  • Can you maybe edit to clear up your schema a bit? I'm not sure I'm following it quite right. What does your shop table look like? – antinescience Mar 24 '13 at 21:38