将WHERE与存储过程一起使用

时间:2017-03-24 23:01:54

标签: sql-server tsql stored-procedures

我在以下代码中收到了WHERE子句的语法错误。 问题是什么?

CREATE PROC spIncreaseHours
(@ID int, @HoursPerWeek DEC, @HourlyRate INT)
AS
INSERT INTO Payments
Values (@HoursPerWeek, @HourlyRate)
WHERE ID = @ID;

2 个答案:

答案 0 :(得分:3)

您可能想要更新:

CREATE PROC spIncreaseHours
(@ID int, @HoursPerWeek DEC, @HourlyRate INT)
AS
UPDATE Payments set 
HoursPerWeek = @HoursPerWeek, 
HourlyRate = @HourlyRate
WHERE ID = @ID;

答案 1 :(得分:1)

您无法将WHEREINSERT一起使用。您要么想要插入新行,要么更新现有行。例如INSERT

CREATE PROC spIncreaseHours
(@ID int, @HoursPerWeek DEC, @HourlyRate INT)
AS
INSERT INTO Payments
Values (@ID, @HoursPerWeek, @HourlyRate);

UPDATE

CREATE PROC spIncreaseHours
(@ID int, @HoursPerWeek DEC, @HourlyRate INT)
AS
UPDATE Payments
SET HoursPerWeek = @HoursPerWeek, 
     HourlyRate = @HourlyRate
WHERE ID = @ID;

当然,还有第三种可能性,您不知道@ID的行是否已存在,因此您可以先进行检查:

CREATE PROC spIncreaseHours
(@ID int, @HoursPerWeek DEC, @HourlyRate INT)
AS
IF EXISTS (SELECT ID FROM Payments WHERE ID = @ID)
    UPDATE Payments
    SET HoursPerWeek = @HoursPerWeek, 
        HourlyRate = @HourlyRate
    WHERE ID = @ID;
ELSE
    INSERT INTO Payments
    Values (@ID, @HoursPerWeek, @HourlyRate);