بازدید: 1114 بازدید

مساله:

من دو جدول دارم و می‌خواهم داده‌ها را از جدول اول Source به جدول دوم Target منتقل کنم. اگر شناسه ID در جدول Source وجود داشته باشد، ستون‌های دیگر را به‌روزرسانی کند؛ و اگر شناسه ID وجود نداشته باشد، رکورد جدیدی را درج کند.

 

Using T-SQL and SSMS with sample data, I have two tables and I want to transfer data from the source table to the target table. If the ID already exists in the target table, update the other columns. If the ID does not exist, insert a new record.

پاسخ:

Let’s say you have two tables, source_table and target_table, with the following structure:

دو جدول ایجاد میکنیم با نام های source_table و target_table

Source table–

CREATE TABLE source_table ( id INT PRIMARY KEY, col1 VARCHAR(50), col2 VARCHAR(50), col3 VARCHAR(50) );

 Target table–

CREATE TABLE target_table ( id INT PRIMARY KEY, col1 VARCHAR(50), col2 VARCHAR(50), col3 VARCHAR(50) );

 

 

 

 

 

 

 

داده های فرضی در آن ثبت میکنیم

 Sample data for source table–

INSERT INTO source_table VALUES

(1, ‘John’, ‘Doe’, ‘johndoe@example.com’), (2, ‘Jane’, ‘Doe’, ‘janedoe@example.com’),

(3, ‘Bob’, ‘Smith’, ‘bobsmith@example.com’);

Sample data for target table–

INSERT INTO target_table VALUES

(1, ‘John’, ‘Doe’, ‘oldemail@example.com’),

(2, ‘Jane’, ‘Doe’, ‘janedoe@example.com’);

و در نهایت با استفاده از دستور Merge مقایسه بین دو جدول را انجام میدهیم و داده ها را به جدول Target منتقل میکنیم

MERGE target_table AS target

USING source_table AS source

ON (target.id = source.id)

WHEN MATCHED THEN

UPDATE SET target.col1 = source.col1, target.col2 = source.col2, target.col3 = source.col3

WHEN NOT MATCHED BY TARGET THEN

INSERT (id, col1, col2, col3) VALUES (source.id, source.col1, source.col2, source.col3);

 

مطالعه بیشتر