我希望能够在将零传递给存储过程时处理参数。如果参数为零,则忽略AND
语句。
这是我的程序:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[OrderLoadAllPaged]
@WarehouseId INT = 0,
@CreatedFromUtc DATETIME = NULL,
@CreatedToUtc DATETIME = NULL
AS
BEGIN
DECLARE @sql NVARCHAR(MAX)
SET NOCOUNT ON;
SELECT TOP 100 *
FROM [Test].[dbo].[Order] WITH (NOLOCK)
WHERE
[Deleted] = 0
AND [WarehouseId] = @WarehouseId
AND [CreatedOnUtc] >= ISNULL(@CreatedFromUtc, '1/1/1900')
AND [CreatedOnUtc] < ISNULL(@CreatedToUtc, '1/1/2999')
END
我想要某种条件,仅在仓库编号大于0的情况下才运行查询的这一部分
AND [WarehouseId] = @WarehouseId
类似:
IF (@WarehouseId > 0)
AND [WarehouseId] = @WarehouseId
我真的很需要这个,因为在数据库中有3个仓库,分别是ID 1、2和3。
如果将其作为零传递,我的查询将失败,因为如果将零作为参数传递,它将不与我需要返回的所有3个仓库匹配。
我认为您想要:
AND ([WarehouseId] = @WarehouseId OR @WarehouseId = 0)
您可以添加案例说明
SELECT TOP 100 *
FROM [Test].[dbo].[Order] with (NOLOCK)
WHERE
[Deleted] = 0
AND [WarehouseId] = case when @WarehouseId>0 then @WarehouseId else [WarehouseId] end
AND [CreatedOnUtc] >= ISNULL(@CreatedFromUtc, '1/1/1900')
AND [CreatedOnUtc] < ISNULL(@CreatedToUtc, '1/1/2999')
另一个选择是最大化使用sqlserver iif
函数
and iif(@WarehouseId = 0, [WarehouseId], @WarehouseId) = [WarehouseId]