0

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=)

2
  • Are you trying to update the ContCount for all cities in the City table? Or do you just want the ContCount for a particular City_ID? Commented Dec 9, 2013 at 0:05
  • It should be updating dynamicaly for all cities after updating,inserting etc. in Adress table Commented Dec 9, 2013 at 0:20

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I've used such code: UPDATE DBO.Cities SET ContactCount = (SELECT COUNT(*) FROM dbo.Adresses WHERE dbo.Adresses.City_ID = dbo.Cities.ID)
0

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)

Comments

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.