2020-08-13

[T-SQL]透過其他資料表更新

DECLARE @target TABLE (
    IDA NVARCHAR(5),
    USERNAME NVARCHAR(50),
    EMAIL NVARCHAR(50),
    DEP NVARCHAR(50)
)


DECLARE @Source TABLE (
    ID NVARCHAR(5),
    USERNAME NVARCHAR(50),
    EMAIL NVARCHAR(50),
    DEP NVARCHAR(50)
)

INSERT INTO @Source(ID,USERNAME) VALUES ('1' ,'aa');
INSERT INTO @Source(ID,USERNAME) VALUES ('2' ,'bb');
 
INSERT INTO @target(IDA) VALUES ('1');
INSERT INTO @target(IDA) VALUES ('2');
INSERT INTO @target(IDA) VALUES ('3');
 
UPDATE @target  SET USERNAME = S.USERNAME
FROM (SELECT ID,USERNAME FROM @Source ) S
WHERE S.ID = IDA
  AND IDA = '1'
 
SELECT * FROM @Source
SELECT * FROM @target

沒有留言:

張貼留言