通过执行更新代码

时间:2013-04-02 17:00:54

标签: sql sql-server tsql updates

我是初学程序员,我正在尝试学习SQL,而且我遇到的问题是我给出的问题是:

  

编写一个接受ISBN号和新建议价格的程序UpdateSuggestedPrice。如果ISBN不存在,请提出错误消息。如果没有错误,请将建议价格更新为新价格。

Create PROCEDURE UpdateSuggestedPrice (@ISBN char(10), @SuggestedPrice smallmoney)
AS
BEGIN
   if @ISBN is null
   Begin
     Raiserror ('Provide a valid ISBN',16,1)
   End
   else
   Begin    
     if (select COUNT(*) from Title where SuggestedPrice = @SuggestedPrice) = 0
     begin
        Select 'Description sucessfully added'

        insert into Title (SuggestedPrice)
        values (@SuggestedPrice)
     End
     Else
        Raiserror ('Description already exists',16,1)
     End
   End

   Return

-- Here I'm trying to execute the procedure, search for ISBN and 
-- then update the suggested price, can someone please tell me 
-- what I'm doing wrong.
execute UpdateSuggestedPrice @ISBN= '1021031040', @SuggestedPrice = '40'

1 个答案:

答案 0 :(得分:1)

您的代码存在多个问题。首先,您要在数据中搜索SuggestedPrice = @SuggestedPrice的记录 - 这实际上应该在ISBN = @ISBN中查找ISBN。您还在存储过程结束时缺少END

我建议重新阅读这个问题。

CREATE PROCEDURE UpdateSuggestedPrice (@ISBN char(10), @SuggestedPrice smallmoney)
AS
BEGIN
   IF @ISBN is null
   BEGIN
     RAISERROR ('Provide a valid ISBN',16,1)
   END
   ELSE
   BEGIN    
     IF (SELECT COUNT(*) FROM Title WHERE ISBN = @ISBN) = 0
     BEGIN
        RAISERROR ('ISBN does not exist.',16,1)
     END
     ELSE
     BEGIN
        SELECT 'Price sucessfully updated.';
        UPDATE Title /* Title is the table to be updated */
        SET SuggestedPrice = @SuggestedPrice /* this is the field to update */
        WHERE ISBN = @ISBN; /* this selects which record to update */
     END
   END
END 
GO
EXECUTE UpdateSuggestedPrice @ISBN= '1021031040', @SuggestedPrice = '40'