我是SQL的初学者,尤其是TSQL。我需要为SQL Server 2008编写一个SP,它将读取符合某些条件的所有记录,然后在不同的结果集中读取它们的相关类别,成分,单位等。为了阅读一个元素我的SP是:
-- Select the recipe
SELECT Recipe.*
FROM Recipe
WHERE Recipe.RecipeId = @RecipeId
-- Select the categories themselves
SELECT Category.*
FROM Category
JOIN RecipeCategory ON RecipeCategory.CategoryId = Category.CategoryId
WHERE RecipeCategory.RecipeId = @RecipeId
-- Select the ingredient information for the recipe
SELECT RecipeIngredient.*
FROM RecipeIngredient
JOIN Recipe ON Recipe.RecipeId = RecipeIngredient.RecipeId
WHERE Recipe.RecipeId = @RecipeId
-- Select the ingredients themselves
SELECT Ingredient.*
FROM Ingredient
JOIN RecipeIngredient ON RecipeIngredient.IngredientId = Ingredient.IngredientId
JOIN Recipe ON Recipe.RecipeId = RecipeIngredient.RecipeId
WHERE Recipe.RecipeId = @RecipeId
-- Select the units that are associated with the ingredients
SELECT Unit.*
FROM Unit
JOIN Ingredient ON Ingredient.UnitId = Unit.UnitId
JOIN RecipeIngredient ON RecipeIngredient.IngredientId = Ingredient.IngredientId
WHERE RecipeIngredient.RecipeId = @RecipeId
如何将其转换为阅读具有Name like '%..%'
由于该表有数百万个食谱,我希望尽可能高效地完成。
答案 0 :(得分:1)
要按名称(带通配符)选择食谱,您可能会改变您的过程以执行以下操作:
-- Get a list of name-matched RecipeIDs
DECLARE @RecipeIDs TABLE (
RecipeID int not null primary key
)
INSERT INTO @RecipeIDs (RecipeID)
SELECT Recipe.RecipeID
FROM Recipe
-- Change the parameter of the proc from @RecipeId to @Name
WHERE Recipe.Name like '%' + @Name + '%'
-- Select the recipes
SELECT Recipe.*
FROM Recipe
WHERE Recipe.RecipeId in (select RecipeID from @RecipeIDs)
-- Select the categories themselves
SELECT Category.*
FROM Category
JOIN RecipeCategory ON RecipeCategory.CategoryId = Category.CategoryId
WHERE RecipeCategory.RecipeId in (select RecipeID from @RecipeIDs)
-- Select the ingredient information for the recipes
SELECT RecipeIngredient.*
FROM RecipeIngredient
JOIN Recipe ON Recipe.RecipeId = RecipeIngredient.RecipeId
WHERE Recipe.RecipeId in (select RecipeID from @RecipeIDs)
-- Select the ingredients themselves
SELECT Ingredient.*
FROM Ingredient
JOIN RecipeIngredient ON RecipeIngredient.IngredientId = Ingredient.IngredientId
JOIN Recipe ON Recipe.RecipeId = RecipeIngredient.RecipeId
WHERE Recipe.RecipeId in (select RecipeID from @RecipeIDs)
-- Select the units that are associated with the ingredients
SELECT Unit.*
FROM Unit
JOIN Ingredient ON Ingredient.UnitId = Unit.UnitId
JOIN RecipeIngredient ON RecipeIngredient.IngredientId = Ingredient.IngredientId
WHERE RecipeIngredient.RecipeId in (select RecipeID from @RecipeIDs)
我首先获取与新@Name参数匹配的所有配方ID,然后使用IN
而不是=
获取结果集。
就性能而言,请确保在尝试优化速度之前先获得正确的结果。但是,如果遇到性能问题,还可以使用其他方法编写查询。例如,如果匹配的ID列表变得很大,您可能更倾向于使用临时表而不是表变量来保留列表,或者只是将名称匹配部分串联到每个选择中。也许RecipeID上的连接会比IN
更快。当然,在所有这些情况下,SQL引擎可能会做同样的事情(毕竟SQL基本上是declarative。表的索引也可以发挥作用。请告诉我们这对您有何影响。