0

I have the following data in a table TABLE1

SessionID
S1
S2
S3

i have the following data in another TABLE2

EmployeeID | Session
1          | NULL
2          | NULL
3          | NULL

What i would like to do is update/Insert each row example

UPDATE table2 SET Session= (SELECT SessionID FROM TABLE1)
INSERT INTO( COPY each row and insert 2nd row session id from table1)

The Expected Result: TABLE2

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

Any insight will help.

Thank you.

3 Answers 3

2

It sounds like you want a row in TABLE2 for every combination of each row currently in TABLE2 and each row in TABLE1. If so...

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
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Daniel ,your way is works. but i face the primary key problem . in the table2 , my employeeid is primary key .so i have tried make session and employee id as candidate key but it fail because my table 2 session is null. any suggestion?
If EmployeeID must be the primary key of TABLE2 then you simply can't do what you want since it will require duplicate values in that column. If you can remove the current key and replace it with a new composite key covering EmployeeID and Session then it will work as long as you never have duplicate Session values for the same EmployeeID. You'll be able to have one NULL value per EmployeeID but no more than that.
1

I would suggest creating a separate Employee table. To insert data to your EmployeeSession (TABLE2):

INSERT INTO EmployeeSession ( EmployeeID, SessionID )
    SELECT Employee.ID, [Session].ID
    FROM Employee, [Session]

1 Comment

thanks but i think daniel's answer is more suitable for my situation
0

I think the MERGE statement helps:

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
;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.