2015-12-09 39 views
1

我在形式序列化到一個XML列在SQL Server表中的數據:找到,如果在SQL Server表的XML列上存在元素

<Form title="Sample Data"> 
    <MyProperty>1234</MyProperty> 
    <Employee> 
    <MyProperty>1234</MyProperty> 
    </Employee> 
</Form> 

元素MyProperty既可以在根級別,或<Employee>下的子元素。

我需要的是一個SQL腳本:看到

  1. 檢查是否存在MyProperty在XML的根目錄(我不關心它的子版本)
  2. 如果不存在,請在根級別插入記錄。

MyProperty的值先前已計算過,我打算將它放入臨時表中,以及具有序列化XML的行的PK。

任何人都可以提供一些指導如何做到這一點?

+1

一個問題請,尤其是當你不知道在哪裏,如何開始。你想先做什麼?我假設:「檢查MyProperty是否存在於XML的根級別」。閱讀有關['存在()'](https://msdn.microsoft.com/en-us/library/ms189869.aspx)方法,並嘗試實施它爲您的情況 – har07

回答

1

第一個問題可以通過使用簡單的XPATH語法來回答,如下所示。

declare @x xml = '<Form title="Sample Data"> 
    <MyProperty>1234</MyProperty> 
    <Employee> 
    <MyProperty>1234</MyProperty> 
    </Employee> 
</Form>'; 


--does MyProperty exist at the root level? 
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @x.nodes('/Form') T(c)); 
if @rootlevelvalue is not null 
begin 
    print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')'; 
end 
else 
begin 
    print 'no, it does not exist at the root level' 
end 

而第二個問題可以用XPath的插入語法來回答。同時

declare @y xml = '<Form title="Sample Data"> 
    <Employee> 
    <MyProperty>1234</MyProperty> 
    </Employee> 
</Form>'; 


--does MyProperty exist at the root level? 
declare @rootlevelvalue nvarchar(max) = (select T.c.value('(MyProperty)[1]','nvarchar(max)') from @y.nodes('/Form') T(c)); 
if @rootlevelvalue is not null 
begin 
    print 'yes, it exists at the root level (value = ' + @rootlevelvalue + ')'; 
end 
else 
begin 
    print 'no, it does not exist at the root level'; 
    set @y.modify('insert <MyProperty>99999</MyProperty>into (/Form)[1]') 
    print 'so we added it.'; 
end 
select @y 
+0

謝謝,關於第一部分: 我用.exist()根據har07的建議檢查元素是否存在於XML中。 – CorribView

相關問題