我必须在sql 2008中编写一个搜索查询,它可以使用多个可选的
parameters..ie。
Date From: ...
Date To: ...
UserType: ...
Customer: ...
User: ...
A user can select any of the above search parameters.
I am planning to use either the separate select statements for different cases, or
to use coalesce etc.
Please suggest what would be best possible way out.
谢谢,
答案 0 :(得分:22)
使用此方法可以避免使用多个IF ELSE条件和动态查询。
SELECT * FROM TBL
WHERE (@Name IS NULL OR Name = @Name)
AND (@Age IS NULL OR Age = @Age)
答案 1 :(得分:8)
你可以写你在哪里这样的事情......
SELECT ......
FROM TABLE
WHERE
(@UserType IS NULL OR UserType = @UserType)
AND
(@Customer IS NULL OR Customer = @Customer)
AND
(@User IS NULL OR User = @User)
AND
(<Similarly Other Conditions>)
答案 2 :(得分:2)
您可以使用动态查询
SELECT @sql=
'SELECT DISTINCT [Test_Id], [Test].[Test_Name], [Test].[Test_Date]
FROM [Test]
WHERE (1 = 1)'
IF @start IS NOT NULL
SELECT @sql = @sql + ' AND ([Test].[Test_Date] >= @start)'
IF @end IS NOT NULL
SELECT @sql = @sql + ' AND ([Test].[Test_Date] <= @end)'
SELECT @paramlist = '@start datetime,
@end datetime'
EXEC sp_executesql @sql, @paramlist,
@start,
@end
你也可以使用不同的查询,但如果你有超过2个参数,那就是非常讨厌的代码
IF(@start IS NULL)
IF(@end IS NULL)
SELECT ...
ELSE
SELECT ...
ELSE
IF(@end IS NULL)
SELECT ...
ELSE
SELECT ...