-1

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

Drew
  • 24,851
  • 10
  • 43
  • 78
  • Use merge statement. – Avi Nov 10 '15 at 04:19
  • what language is this, pseudo language ? – Drew Nov 10 '15 at 04:23
  • look into `insert on duplicate key update`. [Manual Page](http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html) Perhaps that will be of use. It needs a unique key to clash for the update to fire. Here is a [visual example](http://stackoverflow.com/a/32468519) – Drew Nov 10 '15 at 04:24

1 Answers1

0

try this one

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