-1

我有要升级的程序,它在插入之前在拾取数据表中为客户插入新记录

我正在尝试更新它,以便它检查客户端 StatusID 是否在(1、2、6)中。到目前为止我有这个

alter PROCEDURE dbo.InsertPickup
    @ClientID int, --Required ClientID and PickupDate
    @PickupDate date 
AS
   IF NOT EXISTS (SELECT * FROM Pickup 
                  WHERE ClientID = @ClientID 
                    AND MONTH(PickupDate) = MONTH(@PickupDate) 
                    AND YEAR(PickupDate) = YEAR(@PickupDate) )
if exists (select * from clients where statusid in (1,2,6))
      INSERT INTO Pickup (ClientID, PickupDate)
      VALUES (@ClientID, @PickupDate)

但是如果例如状态ID = 5或3或4的客户端,它仍然插入记录是不对的

4

2 回答 2

1

正确的缩进和 BEGIN/END 包装器可以大大有助于发现查询中的问题。我已将检查添加到ClientID并针对PickupDatesargable 进行了测试(以防现在有索引或将来会有索引)。

IF NOT EXISTS 
(
  SELECT 1 
    FROM dbo.Pickup WHERE ClientID = @ClientID
    AND PickupDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, @PickupDate), 0)
    AND PickupDate < DATEADD(MONTH, DATEDIFF(MONTH, 0, @PickupDate)+1, 0)
)
BEGIN
  IF EXISTS
  (
    SELECT 1 
      FROM dbo.clients WHERE ClientID = @ClientID 
      AND statusid IN (1,2,6)
  )
  BEGIN
      INSERT INTO dbo.Pickup (ClientID, PickupDate)
      VALUES (@ClientID, @PickupDate);
  END
END

当然,您也可以在没有所有嵌套IF测试的情况下执行此操作:

INSERT dbo.Pickup(ClientID, PickupDate)
  SELECT @ClientID, @PickupDate
    WHERE EXISTS 
    (
      SELECT 1 FROM dbo.clients WHERE ...
    )
    AND NOT EXISTS 
    (
      SELECT 1 FROM dbo.Pickup WHERE ...
    );
于 2013-04-02T22:16:06.027 回答
1

您没有在第二个语句中过滤您的clients表格,因此它没有按预期工作。尝试:@ClientIDIF EXISTS

if exists (select * from clients where statusid in (1,2,6) AND ClientID = @ClientID)
于 2013-04-02T22:16:46.107 回答