SQL存储过程比较值

时间:2009-04-17 03:37:53

标签: sql-server stored-procedures

假设我有下表

book
-----
id
name
genre
check_out_date
location_id

任何人都可以发布一个高效存储过程的示例,它只更新传入的值与表中当前值不同的book表吗?

即。如果我传入价值观(1,“屠宰场V”,“小说”,2008年10月,54) 表中的值是(1,“Slaughterhouse V,”Fiction“,10/24 / 2009,70), 它只会更新check_out_date和location_id列。

Update Book set check_out_date=@check_out_date (10/24/2009), location_id=@location_id (70).

提前致谢

4 个答案:

答案 0 :(得分:2)

UPDATE book
SET name = @name,
    genre = @genre,
    check_out_date = @check_out_date,
    location_id = @location_id
FROM BOOK
WHERE (id = @id) AND
     (((@name IS NULL AND name IS NOT NULL) OR
       (@name IS NOT NULL AND name IS NULL) OR
       (@name IS NOT NULL AND name IS NOT NULL AND name <> @name)) OR 
      ((@genre IS NULL AND genre IS NOT NULL) OR
       (@genre IS NOT NULL AND genre IS NULL) OR
       (@genre IS NOT NULL AND genre IS NOT NULL AND genre <> @genre)) OR 
     ((@check_out_date IS NULL AND check_out_date IS NOT NULL) OR
       (@check_out_date IS NOT NULL AND check_out_date IS NULL) OR
       (@check_out_date IS NOT NULL AND check_out_date IS NOT NULL AND
        check_out_date <> @check_out_date)) OR 
     ((@location_id IS NULL AND location_id IS NOT NULL) OR
       (@location_id IS NOT NULL AND location_id IS NULL) OR
       (@location_id IS NOT NULL AND location_id IS NOT NULL AND
        location_id <> @location_id)))

答案 1 :(得分:1)

您可能不想这样做,但您也可以先删除具有匹配ID的记录,然后重新插入。

答案 2 :(得分:0)

最有效的选择是在BL或可能的DAL中进行比较,并在那里做出更新或不做出决定。

如果你知道它是一个更新而不是插入,你可能无论如何都在阅读记录。而且可能还有其他验证。在一个地方处理它。

答案 3 :(得分:0)

你说的是一个存储过程,所以没有理由不保持简单并单独更新。

UPDATE book SET name = @name WHERE id = @id and name <> coalesce(@name,name)
UPDATE book SET genre = @genre WHERE id = @id and genre <> coalesce(@genre,genre)
UPDATE book SET check_out_date = @check_out_date WHERE id = @id and check_out_date <> coalesce(@check_out_date,check_out_date)
UPDATE book SET location_id WHERE id = @id and location_id <> coalesce(@location_id,location_id)