Reputation: 408
maybe this question is duplicate or my query in Google wasn't right, but I have a problem) I have a 3 tables: 1. Contact (int ID, nvarchar Name) 2. City (int ID, nvarchar Name, int ContCount) 3. Adress (int ID, int CityID, int ContactID, int Year)
ContCount field - its a number of a Contacts what are living in some City (City.Name). My query for it:
SELECT COUNT(*) FROM dbo.Adresses WHERE dbo.Adresses.City_ID = 1
Here is my question: I need to my ContCount field assign a result of this query. Can you help me? How can I do it?
P.S. Sorry for my English=)
Upvotes: 0
Views: 69
Reputation: 5853
Or you could combine into a single statement. I've never used a CROSS APPLY in an UPDATE statement, but it ought to work:
UPDATE c SET ContCount = b.AddressCount
FROM dbo.City c
CROSS APPLY (SELECT COUNT(1) as AddressCount
FROM dbo.Address a
WHERE a.City_ID = c.City_ID) b
(optional: WHERE c.City_ID = 1
)
Upvotes: 0
Reputation: 56
If you are using TSQL you can use the following code to save that variable:
DECLARE @ContCount as INT
SET @ContCount = (SELECT COUNT(*) FROM dbo.Adresses WHERE dbo.Adresses.City_ID = 1)
Im not quite sure what you want to do next, but you can use it in any query you write next, for example:
DECLARE @ContCount as INT
SET @ContCount = (SELECT COUNT(*) FROM dbo.Adresses WHERE dbo.Adresses.City_ID = 1)
UPDATE City SET ContCount=@ContCount Where ID=1
Upvotes: 1