Вопрос

I'm trying to write an SQL SP where I am inserting the nodes of some xml data - and I want to check this information is not present in the table's column already.

The table is called 'PositionDescriptions' and has 2 columns 'DescriptionId (int)' and 'Description (nvarchar(max)'.

So far I have the following to loop through the code:

@TheRole                xml,

SET @TheRole = '<Descriptions><Description>TheRole Testing 123</Description><Description>TheRole Test again</Description></Descriptions>'

DECLARE @Temp TABLE(description nvarchar(MAX))

INSERT INTO @Temp(description)

SELECT PositionsDescriptions.Description.value('./@Description', 'nvarchar(MAX)') as [Description]
FROM @TheRole.nodes('/Descriptions/Description') as [PositionsDescriptions]([Description]);

I can't seem to work out how to do any if statement which basically says: "If the description is already present in the table, get the description id. Else if the description is not present, insert the description into the table and return the new description id"

I'm new to SPs and SQL so hope this isn't a daft question!

Это было полезно?

Решение

Are you sure you want to do this in the loop? You can insert all description in one query:

;with cte as (
    select
        T.C.value('.', 'nvarchar(max)') as Description
    from @TheRole.nodes('/Descriptions/Description') as T(C)
)
insert into PositionDescriptions (Description)
select c.Description
from cte as c
where not exists (select * from PositionDescriptions as p where p.Description = c.Description)

sql fiddle example

If you really want a loop, use cursor:

declare
    @TheRole xml, @DescriptionId int, @Description nvarchar(max)

set @TheRole = '<Descriptions><Description>TheRole Testing 123</Description><Description>TheRole Test again</Description></Descriptions>'

declare cur1 cursor local fast_forward for
    select
        P.DescriptionId, N.Description
    from (
        select
            T.C.value('.', 'nvarchar(max)') as Description
        from @TheRole.nodes('/Descriptions/Description') as T(C)
    ) as N
        left outer join PositionDescriptions as P on P.Description = N.Description

open cur1
while 1 = 1
begin
    fetch cur1 into @DescriptionId, @Description
    if @@fetch_status <> 0 break

    if @DescriptionId is null
    begin
        insert into PositionDescriptions (Description)
        select @Description

        select @DescriptionId = scope_identity()
    end

    -- do what you want
end
close cur1
deallocate cur1

sql fiddle demo

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top