1

我正在尝试编写一个 SQL SP,我将在其中插入一些 xml 数据的节点 - 我想检查此信息是否已存在于表的列中。

该表称为“PositionDescriptions”,有 2 列“DescriptionId (int)”和“Description (nvarchar(max)”。

到目前为止,我有以下循环代码:

@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]);

我似乎无法弄清楚如何执行任何基本上说的 if 语句:“如果表中已经存在描述,则获取描述 id。否则,如果描述不存在,则将描述插入表中并返回新的描述 ID”

我是 SP 和 SQL 的新手,所以希望这不是一个愚蠢的问题!

4

1 回答 1

0

您确定要在循环中执行此操作吗?您可以在一个查询中插入所有描述:

;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

如果你真的想要一个循环,使用游标:

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

于 2013-09-17T15:05:19.507 回答