如何创建存储过程以根据 Id 和 Name 参数更新 Std_Course 的列,或者如果 Id 和 Name 不存在则插入新行
问问题
5699 次
1 回答
2
尝试这样的事情:
CREATE PROCEDURE dbo.proc_InsertOrUpdate
@ID INT, @Name VARCHAR(50), @StdCourse INT
AS
IF EXISTS (SELECT * FROM dbo.YourTable WHERE ID = @ID AND Name = @Name)
UPDATE dbo.YourTable
SET Std_course = @StdCourse
WHERE ID = @ID AND Name = @Name
ELSE
INSERT INTO dbo.YourTable(ID, Name, Std_Course)
VALUES(@ID, @Name, @StdCourse
更新:由于您使用的是 SQL Server 2008,因此您还可以使用简单的MERGE
语句 - 直接“内联”或在存储过程中。它看起来像这样:
CREATE PROCEDURE dbo.proc_InsertOrUpdate
@ID INT, @Name VARCHAR(50), @StdCourse INT
AS
MERGE dbo.YourTable AS t
USING (SELECT @ID, @Name, @StdCourse) AS Source(ID, NAME, Std_Course)
ON source.ID = t.ID AND source.Name = t.Name
WHEN MATCHED THEN
UPDATE SET Std_Course = @StdCourse
WHEN NOT MATCHED THEN
INSERT(ID, Name, Std_Course)
VALUES(source.ID, source.Name, source.Std_Course);
于 2012-06-18T07:24:30.057 回答