0

我在表 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)

预期结果:表 2

EmployeeID | Session
1          | S1
2          | S1
3          | S1
1          | S2
2          | S2
3          | S2
1          | S3
2          | S3
3          | S3

任何见解都会有所帮助。

谢谢你。

4

3 回答 3

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
于 2012-05-25T06:51:08.340 回答
1

我建议创建一个单独的 Employee 表。要将数据插入到您的 EmployeeSession (TABLE2):

INSERT INTO EmployeeSession ( EmployeeID, SessionID )
    SELECT Employee.ID, [Session].ID
    FROM Employee, [Session]
于 2012-05-25T06:56:15.167 回答
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
;
于 2012-05-25T07:30:49.753 回答