插入每个主表的连接表值

时间:2018-06-06 13:32:27

标签: sql sql-server

我有一个名为StoreTbl的表来存储商店/市场,这个表有一个名为AvailableToAllCities的布尔字段 还有另一个名为CityTbl的表 并且它们之间有一个名为StoreCityJoinTbl

的联接表

经理让我删除字段AvailableToAllCities(或不再使用它);所以我需要为每个商店的所有城市插入连接表, 我可以不使用for循环吗?

1 个答案:

答案 0 :(得分:2)

没有任何类型的DDL,我必须创建自己的DDL,并使用非常有限的数据。但是,这应该足以让你到达那里:

USE Sandbox;
GO
--Sample data set up
CREATE TABLE Store (StoreID int IDENTITY(1,1), StoreName varchar(50), AvailableToAllCities bit)

CREATE TABLE City (CityID int IDENTITY(1,1), CityName varchar(50));

CREATE TABLE CityStores (ID int IDENTITY(1,1), StoreID int, CityID int)
GO

INSERT INTO City (CityName)
VALUES ('London'),('New York'),('Syndey'),('Washington'),('Paris'),('Berlin'),('Shanghai'),('Tokyo');

INSERT INTO Store (StoreName, AvailableToAllCities)
VALUES ('sdgfkljasghdbfkl',1),
       ('dsfjklgh',0),
       ('sdlafiugasdljkbfh',1),
       ('asdfhjklgasdfjkl',1),
       ('sdjlhfbvgajldavfhkl',0);

INSERT INTO CityStores (StoreID, CityID)
VALUES (2,1),(2,3),(2,6),
       (5,1),(5,2),(5,7),(5,8);
GO
--So your current data looks like this

SELECT S.StoreName, C.CityName
FROM Store S
     LEFT JOIN CityStores CS ON S.StoreID = CS.StoreID
     JOIN City C ON CS.CityID = C.CityID
                 OR S.AvailableToAllCities = 1;

GO
--And now the the solution
INSERT INTO CityStores (StoreID,CityID)
SELECT S.StoreID, C.CityID
FROM Store S
     CROSS JOIN City C
WHERE S.AvailableToAllCities = 1;
GO
--Drop the old column
ALTER TABLE Store DROP COLUMN AvailableToAllCities;

GO

--And now the new query:
SELECT S.StoreName, C.CityName
FROM Store S
     JOIN CityStores CS ON S.StoreID = CS.StoreID
     JOIN City C ON CS.CityID = C.CityID;

GO
--Clean up
DROP TABLE Store;
DROP TABLE City;
DROP TABLE CityStores;