我试图检查记录是否存在,然后再进行更新
这是我目前所拥有的:(显然不起作用)
CREATE PROCEDURE dbo.update_customer_m
@customer_id INT ,
@firstname VARCHAR(30) ,
@surname VARCHAR(30) ,
@gender VARCHAR(6) ,
@age INT ,
@address_1 VARCHAR(50) ,
@address_2 VARCHAR(50) ,
@city VARCHAR(50) ,
@phone VARCHAR(10) ,
@mobile VARCHAR(11) ,
@email VARCHAR(30) ,
AS
IF EXISTS
(
SELECT *
FROM dbo.Customer
WHERE CustID = @customer_id
)
BEGIN
UPDATE dbo.Customer
SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender, Address1 = @address_1, Address2 = @address_2, City = @city, Phone = @phone, Mobile = @mobile, Email = @email
WHERE CustID = @customer_id
END
有更好的方法吗?
答案 0 :(得分:3)
为什么要先检查?如果该行不存在,则更新将不更新任何行:
UPDATE dbo.Customer
SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender,
Address1 = @address_1, Address2 = @address_2, City = @city,
Phone = @phone, Mobile = @mobile, Email = @email
WHERE CustID = @customer_id;
不需要if
。
答案 1 :(得分:0)
如果不需要块,首先选择if是否没有行,Update块什么都不做,没有行受影响。
只需在此过程中编写更新。
但也许你想写其他如果这个程序,如果没关系,你可以IF和ELSE。 在IF块中,您可以编写此更新,在ELSE块中,您可以执行另一个需要的操作。
答案 2 :(得分:0)
SELECT *
FROM dbo.Customer
WHERE CustID = @customer_id
//add this
IF @@ROWCOUNT>=1
BEGIN
UPDATE dbo.Customer
SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender, Address1 = @address_1, Address2 = @address_2, City = @city, Phone = @phone, Mobile = @mobile, Email = @email
WHERE CustID = @customer_id
END