I want to update "Grade" Column in "StudentTable" with a WHERE clause of "StudentID"". And if there is no "StudentID" found in "StudentTable" then I want to Insert the data instead.
How can I do this?
You first check if the record exists, if it does perform an update, if it does not exist, it means you will need to insert it.
Here you go:
IF EXISTS(SELECT * FROM StudentTable WHERE StudentID = @MyID)
BEGIN
--exists perform update
UPDATE StudentTable SET Grade = 'A+' WHERE StudentID=@MyID
--other code...
END
ELSE
BEGIN
--record does not exist INSERT it
INSERT INTO StudentTable(MyID, Grade) VALUES (@MyID, 'A+')
--other code...
END
You can use merge: http://www.mssqltips.com/tip.asp?tip=1704
MSDN documentation: http://msdn.microsoft.com/en-us/library/bb510625.aspx
精彩评论