SQL Server:动态where子句

问题:

Ajax建议 – 在食谱中搜索[ n ]成分。 那就是:匹配多种成分的配方。

例如: SELECT Recipes using "flower", "salt"会产生: "Pizza", "Bread", "Saltwater"等等。

表:

 Ingredients [ IngredientsID INT [PK], IngredientsName VARCHAR ] Recipes [ RecipesID INT [PK], RecipesName VARCHAR ] IngredientsRecipes [ IngredientsRecipesID INT [PK], IngredientsID INT, RecipesID INT ] 

查询:

 SELECT Recipes.RecipesID, Recipes.RecipesName, Ingredients.IngredientsID, Ingredients.IngredientsName FROM IngredientsRecipes INNER JOIN Ingredients ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID INNER JOIN Recipes ON IngredientsRecipes.RecipesID = Recipes.RecipesID WHERE Ingredients.IngredientsName IN ('salt', 'water', 'flower') 

我正在使用ASP.NET C#构建我的查询,因为WHERE子句的动态特性。

我咬了一下,我必须在我的代码层中构建查询,而不是使用存储过程/纯SQL,理论上应该更快。

你有没有想过如何将我的代码层中的所有逻辑移动到纯SQL,或者至少我如何优化我正在做的事情的性能?

我正在考虑临时表:

第一步SELECT IngredientsID FROM IngredientsINSERT INTO temp-table

第二步SELECT RecipesName FROM RecipesIngredientsRecipes加入了temp-table.IngredientsID

你有两个选择。 如果您使用的是SQL Server 2008(或Oracle),则可以传入表值参数 。

如果您使用的是SQL Server 2005,则可以使用XML来模拟此function

如果你使用的是早于2005的东西,你需要在一个字符串中连接id并创建一个UDF来解析它们。

你至少可以参数化where clausule以避免SQL注入,类似的东西:

 using System.Data; using System.Data.SqlClient; using System.Text; class Foo { public static void Main () { string[] parameters = {"salt", "water", "flower"}; SqlConnection connection = new SqlConnection (); SqlCommand command = connection.CreateCommand (); StringBuilder where = new StringBuilder (); for (int i = 0; i < parametes.Length; i++) { if (i != 0) where.Append (","); where.AppendFormat ("@Param{0}", i); command.Parameters.Add (new SqlParameter ("Param" + i, parameters [i])); } } } 

根据您处理输入成分的方式,我认为当前的方法存在一些SQL注入风险。

您可以将配线名称附加到可能更快的连接条件。

您还可以对配方的成分进行哈希处理,以便快速查找。