SQL: INSERT NEW RECORDS FROM 1 TABLE TO ANOTHER

Samuel Fernandes

Total Post:159

Points:1117
Posted by  Samuel Fernandes
 1774  View(s)
Ratings:
Rate this:
Hi Everyone!

I want to update table from another table data using stored procedure in SQL server. For example I have two table tbl_1 and tbl_2. I want to copy new insert data of tbl_1 to tbl_2.

my stored procedure as following

CREATE PROCEDURE [dbo].[CHECK_NEW]

AS
begin transaction

declare @tempId int
declare @tempName varchar

DECLARE c1 CURSOR FOR  
SELECT kId, kName
FROM table1

OPEN c1

FETCH NEXT FROM c1  
INTO @tempId, @tempName

WHILE @@FETCH_STATUS = 0  
BEGIN

if (SELECT sId FROM table2) NOT IN(@tempId)
insert into table(sId, name) values(@tempId, @tempName)
END

please help me!

Thanks in advance
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: SQL: Insert new records from 1 table to another

    Hi Samuel!


    You can try as following 

    CREATE PROCEDURE [dbo].[CHECK_NEW]
    AS
    Begin Try
    begin transaction
             Insert into Table2(ulid,Id,Name) 
         Select newid() as ulid, Id,name from Table1 a inner join Table2 b on a.id!=b.id
    Commit
    End Try
    Begin Catch
    RollBack
    End Catch

    I hope it resolve your problem

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!