使用ASP.NET中的存储过程进行更新

时间:2018-08-02 11:07:29

标签: c# sql asp.net sql-server

我已经在SQL Server中创建了一个存储过程,如果记录存在,它将更新表,否则它将在表中插入记录

这是存储过程的代码:

CREATE PROCEDURE [dbo].[insert_update]
    (@sender VARCHAR(50),
     @receiver VARCHAR(50),
     @no INT,
     @mas INT,
     @sha INT,
     @not INT,
     @ever INT,
     @love INT,
     @tele INT)
AS
BEGIN
    IF EXISTS (SELECT 1 
               FROM links
               WHERE sender = @sender
                 AND receiver = @receiver
                 AND no = @no
                 AND mas = @mas
                 AND sha = @sha 
                 AND not = @not
                 AND ever = @ever
                 AND love = @love
                 AND tele = @tele)
    BEGIN
        UPDATE links 
        SET sender = ISNULL(@sender, sender),
            receiver = ISNULL(@receiver, receiver), 
            no = ISNULL(@no, no),
            mas = ISNULL(@mas, mas),
            sha = ISNULL(@sha, sha), 
            not = ISNULL(@not, not),
            ever = ISNULL(@ever, ever),
            love = ISNULL(@love, love),
            tele = ISNULL(@tele, tele) 
        WHERE 
            sender = @sender 
            AND receiver = @receiver
    END
    ELSE
    BEGIN
        INSERT INTO links 
        VALUES (@sender, @receiver, @no, @mas, @sha, @not, @ever, @love, @tele)
    END
END

现在,如果记录已经存在,我只想更新几列,所以这是后面的代码:

sql.Open();

SqlCommand Cmd = new SqlCommand("insert_update", sql);
Cmd.CommandType = CommandType.StoredProcedure;

Cmd.Parameters.AddWithValue("@sender",  Request.QueryString["sender"]);
Cmd.Parameters.AddWithValue("@receiver", Request.QueryString["reciever"]);
Cmd.Parameters.AddWithValue("@no",  Request.QueryString["one".ToString()]);
Cmd.Parameters.AddWithValue("@mas", Request.QueryString["two".ToString()]);
Cmd.Parameters.AddWithValue("@sha", Request.QueryString["three".ToString()]);
Cmd.Parameters.AddWithValue("@not", Request.QueryString["four".ToString()]);
Cmd.Parameters.AddWithValue("@ever", Request.QueryString["five".ToString()]);
Cmd.Parameters.AddWithValue("@love", Request.QueryString["six".ToString()]);
Cmd.Parameters.AddWithValue("@tele", Request.QueryString["seven".ToString()]);

Cmd.ExecuteNonQuery();
sql.Close();

每当我尝试更新时,都会出现错误

  

过程或函数'insert_update'需要未提供的参数'@mas'。

那么如何只更新几列呢?

1 个答案:

答案 0 :(得分:0)

您必须更改stored procedure的定义,以便过程不应期望每个参数的值。我们可以为stored procedure定义中的每个参数指定默认值,如下所示-

create PROCEDURE [dbo].[insert_update]
(
    @sender varchar=null,
    @reciever varchar=null,
    @no int=null,
    @mas int=null,
    @sha int=null,
    @not int=null,
    @ever int=null,
    @love int=null,
    @tele int=null
)......