首页 > 解决方案 > 存储过程传递多个参数,条件结果未按预期工作

问题描述

我正在尝试创建这个存储过程,但它没有按预期工作,所以当我将参数传递给它时,我没有得到结果。

这是我的存储过程,它正在返回结果:

BEGIN
    DECLARE @sql NVARCHAR(MAX)

    SET NOCOUNT ON;

    SELECT TOP 100 *
    FROM [Test].[dbo].[Order] WITH (NOLOCK)
    WHERE [Deleted] = 0
      AND ([Id] = @OrderId OR @OrderId = 0)
      AND ([StoreId] = @StoreId OR @StoreId = 0)
      AND ([WarehouseId] = @WarehouseId OR @WarehouseId = 0)
      // if I insert payment status and statement here no results are returned
      AND [CreatedOnUtc] >= ISNULL(@CreatedFromUtc, '1/1/1900')
      AND [CreatedOnUtc] < ISNULL(@CreatedToUtc, '1/1/2999')
END

如果我在warehouseid 和语句之后添加它,它将停止返回结果:

AND ([PaymentStatusId] = @PaymentStatusId OR @PaymentStatusId = 0)

有谁知道这是为什么?

标签: sql-serverstored-proceduresconditional-statements

解决方案


它的安全使用coalesce()功能包括这些null值。

  and iif(@PaymentStatusId = 0, 1, coalesce([PaymentStatusId], 0)) 
    = iif(@PaymentStatusId = 0, 1, @PaymentStatusId)

推荐阅读