简体   繁体   中英

Insert into table field a result of sql query

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?

PS Sorry for my English=)

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM