以下存储过程有效,但我想知道 - 在SQL Server中处理这种类型的操作是否有最佳实践/模式?从本质上讲,我传递了两个不同的参数。根据传入“criteria”参数的内容,我在where子句中运行一些具有某些特定条件的查询 - 谢谢。
ALTER PROCEDURE [dbo].[Select_Project_Info_By_Value]
(
@value VarChar(50),
@criteria VarChar(50)
)
AS
BEGIN
SET NOCOUNT ON;
if @criteria= 'All'
SELECT some some tables...
FROM dbo.Table1
WHERE (NOT (Status = 'ABC'))
else if @criteria = 'X'
SELECT some some tables...
FROM dbo.Table1
WHERE (Matno LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
else if @criteria = 'Y'
SELECT some some tables...
FROM dbo.Table1
WHERE (ID LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
else if @criteria = 'Z'
SELECT some some tables...
FROM dbo.Table1
WHERE (ProDescr LIKE '%' + @value + '%')
else if @criteria = 'A'
SELECT some some tables...
FROM dbo.Table1
WHERE (CustCode LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
else if @criteria = 'B'
SELECT some some tables...
FROM dbo.Table1
WHERE (ApplName LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
END
答案 0 :(得分:0)
也许是这样的:
SELECT some some tables...
FROM
dbo.Table1
WHERE
(
@criteria= 'All'
AND (NOT (Status = 'ABC'))
)
OR
(
@criteria = 'X'
AND (Matno LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
)
OR
(
@criteria = 'Y'
AND (ID LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
)
OR
(
@criteria = 'Z'
AND (ProDescr LIKE '%' + @value + '%')
)
OR
(
@criteria = 'A'
AND (CustCode LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
)
OR
(
@criteria = 'B'
AND (ApplName LIKE '%' + @value + '%') AND (NOT (Status = 'ABC'))
)
答案 1 :(得分:0)
权威在Erland Sommarskog写的where子句和动态搜索条件中的可选参数的工作。 This article详细说明了每种方法的优缺点(其中有很多方法)该链接适用于SQL 2005及更早版本。对于2008年,请使用此链接(http://www.sommarskog.se/dyn-search-2008.html)
如果我是你,我会审阅这篇文章并选择一种方法,尽管无论你怎么写它都无法真正优化你的查询。您的LIKE '%' + @value + '%'
查询无法使用索引,您将始终执行表扫描。
在这种情况下,您可能会遇到参数嗅探问题,因为不同的输入参数可能会产生非常不同的查询计划或通过代码的路径。此proc可能是WITH RECOMPILE
选项的良好候选者。