开发者

Update or Insert Depending on Whether the Record Already Exists [closed]

开发者 https://www.devze.com 2023-03-22 06:06 出处:网络
It开发者_StackOverflow社区's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical andcannot be reasonably answered in its curr
It开发者_StackOverflow社区's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消