开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜