SQL Server存储过程传递旧值而不是新值

6tqwzwtp  于 2023-01-20  发布在  SQL Server
关注(0)|答案(1)|浏览(160)

这是我的table

search_id search_term clicked count
------------------------------
1        rabbit        0         5
2        airline       1         4

这是我的存储过程:

alter procedure update_item
    (@search_id int,
     @search_term varchar(50),
     @clicked int)
as
begin
    update search_events 
    set search_term= @search_term,
        clicked = @clicked
    where search_id = @search_id
end

--exec update_item @search_id=1,@search_term='rabbit',@clicked=0

我创建了一个存储过程并传递了两个参数。
我只想传递一个参数来更新记录,第二个参数值将是旧值。
传递带有旧值的参数是可能的。
例如:

exec update_item @search_id= 1, @search_term= 'pass here old value that it is rabbit', @clicked = 1

仅更新单击的值,使其从0变为1。

5cnsuln7

5cnsuln71#

如果只需要一个参数,可以使用简单的if语句,并在值为空时省略set子句

CREATE PROCEDURE update_item (
    @search_id INT
    ,@search_term VARCHAR(50)
    ,@clicked INT
    )
AS
BEGIN
    IF (@search_term IS NULL)
        UPDATE search_events
        SET clicked = @clicked
        WHERE search_id = @search_id
    ELSE
        UPDATE search_events
        SET search_term = @search_term
            ,clicked = @clicked
        WHERE search_id = @search_id
END

如果你有更多的参数需要检查,那么你需要动态地构建update语句。下面是一个基本的例子:

ALTER PROCEDURE update_item (
    @search_id INT
    ,@search_term VARCHAR(50)
    ,@clicked INT
    )
AS
BEGIN
    DECLARE @Sql NVARCHAR(4000) = N'UPDATE search_events SET ',
            @Params NVARCHAR(300) = N'@search_id INT, @search_term VARCHAR(50), @clicked INT'
    
    IF (@search_term IS NOT NULL)
        SET @Sql = @Sql + ' search_term = @search_term,'

    SET @Sql = @Sql + ' clicked = @clicked'

    SET @Sql = @Sql + ' WHERE search_id = @search_id' 
    
    EXEC sp_executesql @Sql, @Params, @search_id=@search_id, @search_term=@search_term, @clicked=@clicked
END

相关问题