我将描述我想要实现的目标:
我将一个带有名称值对的 xml 传递给 SP,我将其放入表变量中,比如说@nameValuePairs
. 我需要检索与名称-值对(属性、另一个表)完全匹配的表达式(一个表)相关联的 ID 列表。
这是我的架构:
表达式表--> (expressionId, attributeId)
属性表--> (attributeId, attributeName, attributeValue)
在尝试了使用动态 SQL 和邪恶游标的复杂内容(有效但速度非常慢)之后,这就是我现在所拥有的:
--do the magic plz!
-- retrieve number of name-value pairs
SET @noOfAttributes = select count(*) from @nameValuePairs
select distinct
e.expressionId, a.attributeName, a.attributeValue
into
#temp
from
expressions e
join
attributes a
on
e.attributeId = a.attributeId
join --> this join does the filtering
@nameValuePairs nvp
on
a.attributeName = nvp.name and a.attributeValue = nvp.value
group by
e.expressionId, a.attributeName, a.attributeValue
-- now select the IDs I need
-- since I did a select distinct above if the number of matches
-- for a given ID is the same as noOfAttributes then BINGO!
select distinct
expressionId
from
#temp
group by expressionId
having count(*) = @noOfAttributes
人们可以请检查一下,看看他们是否能发现任何问题?有没有更好的方法来做到这一点?
任何帮助表示赞赏!