1

我是 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 '%..%'

由于桌子上有数百万种食谱,我想尽可能高效地完成它。

4

1 回答 1

1

要按名称(使用通配符)选择食谱,您可以更改您的 proc 以执行以下操作:

-- 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 本质上是声明性的)。表的索引也可以发挥作用。请让我们知道这对您有何影响。

于 2012-07-24T20:21:00.393 回答