Click here to Skip to main content
15,906,816 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Education (Table Name)
Studid Mobile
1
2

Student (Table Name)
Studid
1
2
3
4

Temporary (Table Name)
Studid Mobilenum
1 9789512450
2 9789512650
3 9789455564
4 9785654450
5 9785657888
6 9789518780


I want to compare the Temptable and Studenttable studid.
if Temptable and Studenttable studid matches update the mobileno of particular studid in Studenteducation table

if Temptable and Studenttable studid not matches insert the student id and mobileno of particular studid in Studenteducation table.

for that how can i write the store procedure and insert and update those values in Studenteducation table.

Rgds,
Narasiman P.
Posted

Hello,
Please try below SP and let me know if it helps.
SQL
CREATE PROCEDURE sp_update_student_mobile
AS
BEGIN
MERGE Education AS edu
USING (SELECT t.StudId,MobileNum FROM TempTable t LEFT JOIN Student s ON t.StudId = s.StudId) AS tmp
ON edu.StudId = tmp.StudId
WHEN MATCHED THEN UPDATE SET edu.MobileNo = tmp.MobileNum
WHEN NOT MATCHED THEN
INSERT(StudId,MobileNo)
VALUES(tmp.StudId,tmp.MobileNum);
END

Thanks,
Hitesh Varde
 
Share this answer
 
Try below approach.

For case where Temp Table and Student table matched

SQL
UPDATE t1
  SET t1.Mobile = t2.MobileNum
  FROM Edutcation  AS t1
  INNER JOIN Student AS t2 ON t1.Studid= t2.Studid
  INNER JOIN TemporaryTbl AS t3 ON t1.Studid= t3.Studid


For case where Temp Table and Student table does not match

SQL
INSERT INTO Education (StudId, Mobile)
SELECT StudID, MobileNum
FROM TempTbl T
LEFT OUTER JOIN Student S ON T.StudID = S.StudID
WHERE S.StudID is null
 
Share this answer
 

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