Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

c# - SQL Server: Dynamic where-clause

Problem:

Ajax suggest-search on [n] ingredients in recipes. That is: match recipes against multiple ingredients.

For instance: SELECT Recipes using "flower", "salt" would produce: "Pizza", "Bread", "Saltwater" and so forth.

Tables:

Ingredients [
    IngredientsID INT [PK],
    IngredientsName VARCHAR
]

Recipes [
    RecipesID INT [PK],
    RecipesName VARCHAR
]

IngredientsRecipes [
    IngredientsRecipesID INT [PK],
    IngredientsID INT,
    RecipesID INT
]

Query:

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')

I am currently constructing my query using ASP.NET C# because of the dynamic nature of the WHERE clause.

I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster.

Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing?

I am thinking along the lines of temporary tables:

Step one: SELECT IngredientsID FROM Ingredients and INSERT INTO temp-table

Step two: SELECT RecipesName FROM Recipes joined with IngredientsRecipes joined with temp-table.IngredientsID

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a table value parameter.

If you're using SQL Server 2005, you can use XML to simulate this capability

If you're using something earlier than 2005, you need to concatenate the ids in a single string and create a UDF to parse them.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...