Home > DeveloperSection > Forums > SQL: Insert new records from 1 table to another
Samuel Fernandes
Samuel Fernandes

Total Post:154

Points:1082
Posted on    May-09-2013 4:09 AM

 MSSQL Server MSSQL Server 
Ratings:


 1 Reply(s)
 1431  View(s)
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


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-09-2013 8:02 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick