Click here to Skip to main content
14,838,162 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

Can you please help me on this anybody.
In side SP,
I have one Table T1 have many columns and many records, from this data insert into anther table T2 while inserting into Table T2 I need to check ID is exist or not if its exist do the updating with many records or do inserting data.
Please help me on this.
Advanced thank you.
Regards,
Narasimha
Posted

1 solution

Here is a sample approach

I have created 2 temp tables "#SampleTable1" and "#SampleTable2" and inserted some data into it as shown below
SQL
CREATE TABLE #SampleTable1
(
	ID INT,
	[Name] VARCHAR(100)
)

CREATE TABLE #SampleTable2
(
	ID INT,
	[EmpName] VARCHAR(100)
)

INSERT INTO #SampleTable1
SELECT 1, 'James' UNION ALL
SELECT 2, 'Scott' UNION ALL
SELECT 3, 'Rob' UNION ALL
SELECT 4, 'Tom' 


INSERT INTO #SampleTable2
SELECT 1, 'James s' UNION ALL
SELECT 2, 'Tom s' 


Next I will update the EmpName column in Sample table 2 with the names in sample table 1 based on the ID column.
SQL
--Update Existing Records in Sample Table 2
UPDATE ST2
SET ST2.[EmpName] = ST1.[Name]
FROM #SampleTable1 ST1
INNER JOIN #SampleTable2 ST2 ON ST1.ID = ST2.ID


Next insert records that don't exist in sample table 2 from sample table 1 as shown below
SQL
--Insert New Records to Sample Table 2
INSERT #SampleTable2
SELECT ST1.ID, ST1.[Name]
FROM #SampleTable1 ST1
LEFT JOIN #SampleTable2 ST2 ON ST1.ID = ST2.ID
WHERE ST2.ID IS NULL
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900