Join requires all to exist
Posted on 2008-10-10
I have a tricky JOIN problem.
My stored procedure takes a xml in-parameter in which all rows together forms an unique identity. The number of rows is dynamic, e.g., there could be one row, two rows or even three rows that makes up the identity.
<SourceItem ItemValue="S1IV1" SequenceNo="1"/>
<SourceItem ItemValue="S1IV2" SequenceNo="2"/>
<SourceItem ItemValue="S1IV3" SequenceNo="3"/>
The corresponding table defining the identity looks as this:
CREATE TABLE [dbo].[MappingSourceItem](
[MappingSourceItemID] [int] IDENTITY(1,1) NOT NULL,
[MappingSourceID] [int] NOT NULL,
[ItemValue] [varchar](200) NOT NULL,
[SequenceNo] [int] NOT NULL
) ON [PRIMARY]
with the content
MappingSourceItemID MappingSourceID ItemValue SequenceNo
106; 43; S1IV1; 1
107; 43; S1IV2; 2
108; 43; S1IV3; 3
109; 44; S1IV1; 1
110; 44; S1IV2; 2
I then want to find out if the identity given in the example xml exists in the database.
As you can see it does for MappingSourceID=43 since all three rows in the xml mathes.
For MappingSourceID=44 it does not match since only the two first match. How do I write such a join where all rows must match?
My attempt below does not work since it returns all rows matching and does not care that all of them dont match.
DECLARE @Source varchar(MAX)
SET @Source = '<ROOT><SourceItem ItemValue="S1IV1" SequenceNo="1"/><SourceItem ItemValue="S1IV2" SequenceNo="2"/><SourceItem ItemValue="S1IV3" SequenceNo="3"/></ROOT>'
DECLARE @DocHandleSource int
EXEC sp_xml_preparedocument @DocHandleSource OUTPUT, @Source
SELECT * FROM MappingSourceItem AS msi
JOIN OPENXML (@DocHandleSource, '/ROOT/SourceItem',1)
WITH (ItemValue varchar(200), SequenceNo int) AS s
ON msi.ItemValue = s.ItemValue AND msi.SequenceNo = s.SequenceNo
WHERE msi.MappingSourceID = 44
will return the two rows for MappingSourceID=44 but I want it to return 0 rows since not all match.