是否可以编写非动态SQL来匹配具有动态数量的“属性”的行?

时间:2011-09-11 17:32:01

标签: sql

想象一下,我有两张桌子。

Document
  int  DocumentId (PK)
  char DocumentName

Attribute
  int  DocumentId (FK)
  char AttributeName
  char AttributeValue

是否可以编写非动态选择语句,以便我选择与DocumentNameAttributeName对匹配的AttributeValue个?

1 个答案:

答案 0 :(得分:4)

-- Use a table of name,value pairs to search for
DECLARE @wanted TABLE (AttribitedName ..., AttributeValue ...)

INSERT @wanted VALUES ('Colour', 'Blue')
INSERT @wanted VALUES ('Status', 'Draft')

SELECT
   *
FROM
   Document D
WHERE
   EXISTS (SELECT *
        FROM
             Attribute A
             JOIN
             Wanted W ON A.AttributeName = W.AttributeName AND A.AttributeValue = W.AttributeValue
        WHERE
             D.DocumentId = A.DocumentId
        -- do we match all terms that are in Wanted per DocumentID?
        GROUP BY
             A.DocumentId
        HAVING
             COUNT(*) = (SELECT COUNT(*) FROM Wanted)
            )