简体   繁体   中英

Insert a record and also update existing records

hi there i was trying to right a Proc for a DataLoad when you want to insert records on a Table1 based on Table2

This is what i came of with it has 2 condition

1) if the record does not exist create a new row of record 
2) if the record already exist update the record based on keys 

this is my proc need some help thanks

DECLARE @TableKey INT --(it is passed by the user proc param),
DECLARE @TableCount INT,
DECLARE @CLassKey INT,

SELECT @TableCount=  COUNT(*) FROM Table1 WHERE Tablekey= @TableKey

INSERT INTO @CLassKey 

SELECT Distinct c.PK_ClassKey FROM CLASS as c 
INNER JOIN BOOK as B ON B.FK_ClassKey=C.PK_ClassKEy

IF ((SELECT COUNT(*) FROM @ClassKey) > 0 AND @TableCount= 0)--- this will check 
BEGIN
Insert into NOTE 
n.note 
Select 
c.note
FROM Class where c.FK_Note = n.PK_Note.
END

---- this will just insert for the first time.. How do i update it any idea as the records are only inserted for the first time put does not update using the same format thanks a lot

try this one

INSERT INTO table_name (id,col2,col3) 
VALUES (value_id,value2,value3)
ON DUPLICATE KEY UPDATE 
col2=value2,
col3=value3;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM