SQL Server:动态where子句

cll*_*pse 5 c# sql-server performance

问题:

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
]
Run Code Online (Sandbox Code Playgroud)

查询:

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')
Run Code Online (Sandbox Code Playgroud)

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

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

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

我正在考虑临时表:

第一步:SELECT IngredientsID FROM IngredientsINSERT INTO temp-table

第二步:SELECT RecipesName FROM Recipes加入IngredientsRecipes加入temp-table.IngredientsID

Mic*_*own 7

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

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

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