像这样:
SELECT Property_1, Property_2 FROM MyObject
WHERE (Property_1 = @Property_1 OR @Property_1 = -1)
AND (Property_2 = @Property_2 OR @Property_2 = -1)
AND
为您的每个属性添加更多语句
每当将参数设置为-1
相应的AND
子句时,将始终评估为 true,从而返回该属性的任何值。
带有 5 个参数的示例 T-SQL 脚本如下所示:
CREATE PROCEDURE [dbo].[EnterYourSprocNameHere]
@property_1 INT = -1
,@property_2 INT = -1
,@property_3 INT = -1
,@property_4 INT = -1
,@property_5 INT = -1
AS
BEGIN
SELECT property_1, property_2, property_3, property_4, property_5
FROM MyObject
WHERE (Property_1 = @property_1 OR @property_1 = -1)
AND (Property_2 = @property_2 OR @property_2 = -1)
AND (Property_3 = @property_3 OR @property_3 = -1)
AND (Property_4 = @property_4 OR @property_4 = -1)
AND (Property_5 = @property_5 OR @property_5 = -1)
END
如果您想传递 null 而不是 -1,请使用以下脚本:
CREATE PROCEDURE [dbo].[EnterYourSprocNameHere]
@property_1 INT = NULL
,@property_2 INT = NULL
,@property_3 INT = NULL
,@property_4 INT = NULL
,@property_5 INT = NULL
AS
BEGIN
SELECT property_1, property_2, property_3, property_4, property_5
FROM MyObject
WHERE (Property_1 = @property_1 OR @property_1 IS NULL)
AND (Property_2 = @property_2 OR @property_2 IS NULL)
AND (Property_3 = @property_3 OR @property_3 IS NULL)
AND (Property_4 = @property_4 OR @property_4 IS NULL)
AND (Property_5 = @property_5 OR @property_5 IS NULL)
END