表TABLE1中有以下数据
SessionID
S1
S2
S3
我在另一个TABLE2中有以下数据
EmployeeID | Session
1 | NULL
2 | NULL
3 | NULL
我想要做的是更新/插入每一行 示例
UPDATE table2 SET Session= (SELECT SessionID FROM TABLE1)
INSERT INTO( COPY each row and insert 2nd row session id from table1)
预期结果: TABLE2
EmployeeID | Session
1 | S1
2 | S1
3 | S1
1 | S2
2 | S2
3 | S2
1 | S3
2 | S3
3 | S3
任何见解都会有所帮助。
谢谢。
答案 0 :(得分:2)
听起来你想在TABLE2中为TABLE2中每行和TABLE1中每一行的每个组合添加一行。如果是的话......
BEGIN TRAN
SELECT * INTO #temp FROM TABLE2
DELETE TABLE2
INSERT TABLE2
(
EmployeeID,
Session
)
SELECT
temp.EmployeeID,
TABLE1.SessionID
FROM TABLE1 CROSS JOIN #temp temp
DROP #TEMP
COMMIT TRAN
答案 1 :(得分:1)
我建议创建一个单独的Employee表。要将数据插入EmployeeSession(TABLE2):
INSERT INTO EmployeeSession ( EmployeeID, SessionID )
SELECT Employee.ID, [Session].ID
FROM Employee, [Session]
答案 2 :(得分:0)
我认为MERGE
语句有助于:
MERGE INTO TABLE2 t2
USING (SELECT t2.EmployeeID, t1.SessionID
FROM TABLE2 t2
CROSS JOIN TABLE1 t1) t
ON t2.EmployeeID = t.EmployeeID AND t2.Session = t.SessionID
WHEN NOT MATCHED BY TARGET THEN
INSERT (EmployeeID, Session) VALUES(t.EmployeeID, t.SessionID)
WHEN NOT MATCHED BY SOURCE THEN
DELETE
;