防止存储过程的NULL值INSERT

时间:2014-12-05 20:57:29

标签: sql-server tsql stored-procedures insert

如果第二个表有任何数据,我正在处理一个存储过程,该存储过程应该使用来自另一个表Order_TruckDelivery的信息更新表Basket_TruckDelivery。每个表中有两列:int iddatetime列,名为TruckDeliveryDate。如果Basket_TruckDelivery具有为当前购物篮ID存储的日期,则将该日期插入Order_TruckDelivery表。

现在,无论INSERT表中是否有任何内容,Basket_TruckDelivery都会执行,这会导致TruckDelveryDateOrder_TruckDelivery列的NULL值柱。我想防止这种情况发生,但我不完全确定如何发生。基本上,我只想在INSERT表中执行Order_TruckDelivery,如果TruckDeliveryDateBasket_TruckDelivery的值不为空或为空。

这就是我到目前为止......我对存储过程做了很多工作,所以我不确定我错过了什么......

ALTER PROCEDURE [dbo].[SaveTruckIntoOrder]
    @BasketID INT, 
    @OrderID INT
AS
BEGIN
   -- SET NOCOUNT ON added to prevent extra result sets from
   -- interfering with SELECT statements.
   SET NOCOUNT ON;

   -- Insert statements for procedure here
   DECLARE
      @TruckDeliveryDate DATETIME

   IF(EXISTS(SELECT uidBasket FROM [Basket_TruckDelivery] WHERE [uidBasket] = @BasketID))
   BEGIN 
        SELECT
            @TruckDeliveryDate = [TruckDeliveryDate] 
        FROM 
            [Basket_TruckDelivery] 
        WHERE 
            [uidBasket] = @BasketID
   END

   BEGIN
       INSERT INTO [Order_TruckDelivery] ([uidOrder], [TruckDeliveryDate])
       VALUES (@OrderID, @TruckDeliveryDate)
   END
END

1 个答案:

答案 0 :(得分:0)

ALTER PROCEDURE [dbo].[SaveTruckIntoOrder] @BasketID INT
    ,@OrderID INT
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @TruckDeliveryDate DATETIME

    IF (
            EXISTS (
                SELECT uidBasket
                FROM [Basket_TruckDelivery]
                WHERE [uidBasket] = @BasketID
                )
            )
    BEGIN
        SELECT @TruckDeliveryDate = [TruckDeliveryDate]
        FROM [Basket_TruckDelivery]
        WHERE [uidBasket] = @BasketID
    END

    IF (
            @TruckDeliveryDate IS NOT NULL
            AND @TruckDeliveryDate != ''
            )
    BEGIN
        INSERT INTO [Order_TruckDelivery] (
            [uidOrder]
            ,[TruckDeliveryDate]
            )
        VALUES (
            @OrderID
            ,@TruckDeliveryDate
            )
    END
END