适当的IF EXISTS结构

时间:2014-11-19 19:19:18

标签: sql-server stored-procedures

我遇到了存储过程的问题,它的更新次数超过了需要更新的特定行。

该表包含SiloNumber,GreenBeanPartNumber和CloseGate列。筒仓可以存储任何类型的绿豆,并且该表跟踪每种类型的绿豆的最后CloseGate设置,以便下次将绿豆放置在筒仓中时使用。

随着时间的推移,一个孤岛将有多个条目,每种类型的绿豆一个:

SiloNumber | GreenBeanPartNumber | CloseGate

 30     |      1120           |   1.5
 30     |      1234           |   .5
 30     |      3213           |   2.0
 30     |      3453           |   1.1
 30     |      6522           |   1.8

目前,当存储过程更新特定SiloNumber&的CloseGate值时。 GreenBeanPartNumber,它将Silo的所有CloseGate值更改为相同的数字。

SiloNumber | GreenBeanPartNumber | CloseGate

 30     |      1120           |   1.5
 30     |      1234           |   1.5
 30     |      3213           |   1.5
 30     |      3453           |   1.5
 30     |      6522           |   1.5

以下是用于执行更新的存储过程:

ALTER PROC [Controls].[Spclosesettings] @SiloNumber VARCHAR (50),
                                        @GBPartNo   VARCHAR (50),
                                        @value      INT,
                                        @SlowFill   VARCHAR(50) output,
                                        @CloseGate  VARCHAR(50) output
AS
  BEGIN
      IF EXISTS (SELECT closegate
                 FROM   controls.SiloDischargeSettings
                 WHERE  SiloNumber = @SiloNumber
                        AND GreenBeanPartNumber = @GBPartNo)
        UPDATE controls.SiloDischargeSettings
        SET    closegate = @value
        WHERE  GreenBeanPartNumber = @GBPartNo
  END 

我做了一些搜索,然后BEGIN和END在IF EXISTS语句之外,这看起来应该有效。

1 个答案:

答案 0 :(得分:0)

ALTER Proc  [Controls].[spCloseSettings]

 @SiloNumber VarChar (50)
,@GBPartNo Varchar (50)
,@value int 
,@SlowFill varchar(50) output
,@CloseGate  varchar(50) output 
AS
BEGIN

    update t                            
      set t.closegate = @value
    FROM controls.SiloDischargeSettings t
    where t.GreenBeanPartNumber = @GBPartNo
     AND EXISTS (select 1 
                 from controls.SiloDischargeSettings 
                 where SiloNumber          = @SiloNumber 
                   and GreenBeanPartNumber = @GBPartNo
                   and t.GreenBeanPartNumber = GreenBeanPartNumber )

     IF (@@ROWCOUNT > 0)
       SELECT @SlowFill  = @SiloNumber  --<-- only guessing here 
             ,@CloseGate = @value
End