开发者

INSERT INTO a table if NOT EXISTS and then INSERT Duplicate records into Another Table

开发者 https://www.devze.com 2023-04-12 08:28 出处:网络
I am 开发者_C百科writing a stored procedure for the last 2 days and I am not able to figure it out.

I am 开发者_C百科writing a stored procedure for the last 2 days and I am not able to figure it out.

Task: I have a table "table 1" which has some rows in it with "Appointment No" as primary ID.

There is another table "table 1_copy" which is identical to table 1 with primary key not necessary.

I want to insert "first Name " and "last name" into "table 1". However if that record exists already in ""table 1" then those dup records should be inserted into "tabel 1_copy" and the non dups into "table 1"

So in short I insert new records with new "Appointment no" into "table 1" and the duplicate appointment no which already exist in table 1 , into table 1_copy.

I could figure out the insert into if NOT EXISTS PART but am struggling to capture the dups and insert into "table 1_copy"

Please help me.

Thanks in advance


Something like the following ought to work:

IF NOT EXISTS (SELECT * FROM table_1 WHERE FirstName=@FirstName AND LastName=@LastName)
   INSERT INTO table_1 ... 
ELSE
   INSERT INTO table_1_copy ...


I guess you could do something like below

 IF NOT EXTIST (SELECT 'X' FROM TABLE1 WHERE FirstName = @FirstName AND LastName =    @LastName)
 BEGIN
INSERT INTO TABLE1 (BLAH, BLAH)
 END
 ELSE
INSERT INTO TABLE1_COPY 
SELECT BLAH, BLAH FROM TABLE1 WHERE FirstName = @FirstName AND LastName = @LastName
 END
0

精彩评论

暂无评论...
验证码 换一张
取 消