Вы не описали , почему вы обрабатываете XML, поэтому я угадаю.Похоже, что вы ищете конкретное значение firstname
в таблице temps
, и если оно не найдено, вы добавляете его.Я продемонстрирую с табличной переменной, @names
.
-- Assume you have a table [temps] with
-- a column [name], and you want to find
-- the new/missing firstnames from an XML
-- fragment and insert the new firstnames into
-- the [temps] table
-- Example:
--DECLARE [temps] TABLE (name VARCHAR(20))
--INSERT [temps] (name) VALUES ('Michael')
-- Create a temporary table to hold the XML firstname values
DECLARE @names TABLE (firstname VARCHAR(20))
DECLARE @x xml
SET @x =
'<authors>
<author>
<firstname>Michael</firstname>
<lastname>Howard</lastname>
</author>
<author>
<firstname>David</firstname>
<lastname>LeBlanc</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
<author>
<firstname>adad</firstname>
<lastname>asdad</lastname>
</author>
</authors>'
-- Extract the firstnames from the XML and insert the names
-- into the temp table variable
INSERT INTO @names(firstname)
SELECT x.author.value('firstname[1]', 'varchar(20)') AS firstname
FROM @x.nodes('/authors/author') AS x(author)
-- Use a left outer join query to identify the new/missing names
-- in the temp table and then insert the names into [temps].
-- The WHERE condition specifies rows that exist in @firstnames
-- but do not exist (are NULL) in [temps].
INSERT temps (name)
SELECT nam.firstname
FROM @names nam LEFT OUTER JOIN
temps tmp ON (nam.firstname = tmp.name)
WHERE tmp.name IS NULL
LEFT OUTER JOIN используется с условием WHERE для идентификации имен, которые находятся в табличной переменной @firstnames, а не в [firstnames]Таблица.По возможности старайтесь избегать перебора данных в SQL и пытаться использовать операции на основе множеств.