使用存储过程搜索多个表

时间:2015-08-19 18:38:31

标签: sql-server

我有两个表车辆和车辆返回(它在代码中拼写错误),我正在尝试创建一个存储过程,我可以输入引擎号,它将搜索车辆和车辆返回,看看它是否匹配引擎号和它在任何一个表中的标准,但每次只有工作的东西是引擎号不在任何一个表中这里是我的代码

create procedure outbound
(
  @eng varchar(25)
)
AS
BEGIN
   BEGIN TRAN
   DECLARE @eng_num VARCHAR(25)
   DECLARE @eng_num2 VARCHAR(25)


 /* SELECT @eng_num= Engine_num from Vehicle where  Engine_num=@eng and Status=1 
  SELECT @eng_num2= Engine_num from Vehicle_retuns where Engine_num=@eng

    IF(@eng=@eng_num)
    begin
        UPDATE Vehicle SET Description_of_Vehicle='Vehicle has ben sent to Manufactory',Status=0 where Engine_num=@eng_num
    end
    ELSE IF(@eng=@eng_num2)
    begin
        UPDATE Vehicle_retuns SET purpose='Vehicle has ben sent to Manufactory',Status=0 where Engine_num=@eng_num2
    end*/ the lines of code that is the error is occuring
    ELSE
    SELECT 'No such Engine number was found'

   IF(@@ERROR<>0)
   BEGIN
     SELECT 'An unexpected error has occur'
     ROLLBACK TRANSACTION    
     RETURN -1
   END
   COMMIT TRANSACTION
END

1 个答案:

答案 0 :(得分:0)

这是我认为可能需要的粗略草图。单个更新不需要使用显式事务。此外,我强烈建议您查看规范化您的消息,而不是在任何地方对这些长字符串进行硬编码。不确定您是否真的要根据状态值设置描述或目的列。我宁愿看到那些是查找值的外键,但也许这在这里不起作用。我还建议您不要使用&#34; status&#34;等列名。出于多种原因,使用保留字是有问题的。最后但同样重要的是,您应该使用try / catch块而不是检查@@ ERROR。

- EDIT-- 这里有一些新代码可以处理您确实需要两次更新的事实。我最初错过了这个。

create procedure outbound
(
  @eng varchar(25)
)
AS
BEGIN
    IF EXISTS 
    (
        SELECT Engine_num 
        from Vehicle 
        where  Engine_num = @eng

        UNION ALL

        SELECT Engine_num 
        from Vehicle_retuns 
        where Engine_num = @eng
    )
    BEGIN
        BEGIN TRY
            BEGIN TRANSACTION

            UPDATE Vehicle 
                SET Description_of_Vehicle = 'Vehicle has ben sent to Manufactory'
                    , Status = 0 
                where Engine_num = @eng
                    AND Status = 1


            UPDATE Vehicle_retuns 
                SET purpose = 'Vehicle has ben sent to Manufactory'
                    , Status = 0 
                where Engine_num = @eng

            COMMIT TRANSACTION
        END TRY
        BEGIN CATCH
            SELECT 'An unexpected error has occurred.'
            --I would prefer a message here including the error message and error number instead of just "It failed".
        END CATCH
    END    

    ELSE
        SELECT 'No such Engine number was found'
END