插入记录并更新现有记录

时间:2015-11-10 04:16:57

标签: mysql

嗨,当你想根据Table2在Table1上插入记录时,我试图为Proc一个DataLoad

这就是我的想法 它有2个条件

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 

这是我的过程需要一些帮助谢谢

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

----这将是第一次插入.. 我如何更新它的任何想法因为记录只是第一次插入put不使用相同的格式更新非常感谢

1 个答案:

答案 0 :(得分:0)

尝试这个

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