创建存储过程以修改行(如果存在),如果不存在则将新行插入表中

时间:2012-06-18 07:20:44

标签: sql-server-2008 tsql stored-procedures

enter image description here

如何根据Id和Name参数创建存储过程以更新Std_Course的列,如果Id和Name不存在,则插入新行

1 个答案:

答案 0 :(得分: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);