我有3张桌子:
Visitor table
VisitorId (pk)
Name
Phone
Country table
CountryId (pk)
Name
Code
Travels table
TravelId (pk)
CountryId (fk)
VisitorId (fk)
IsVisited (bool)
我希望该foreach国家能够在Travels
表格中为CountryId
创建包含VisitorId
,false
和IsVisited
的其他内容。
更新
INSERT INTO Travels (CountryId, VisitorID, IsVisisted)
SELECT Visitor.VisitorId, Country.CountryId, 1 FROM Visitor, Country
答案 0 :(得分:1)
你应该写为:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM -- 0 = false for IsVisited
(
-- STEP1: first create a combination for all visitor Id and country Id
-- and get all the combinations which are not there in existing Travels table
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
EXCEPT
SELECT CountryId,VisitorId
FROM @Travels
) AS T
否则,如果您想在Country
和Visitor
中为每个组合创建一个条目,请写为:
-- STEP2: Insert records:
INSERT INTO @Travels
SELECT CountryId,VisitorId,0 FROM
(
-- STEP1: first create a combination for all visitor Id and country Id
SELECT C.CountryId,V.VisitorId
FROM @Country C
CROSS JOIN @Visitor V
) AS T
SELECT * FROM @Travels