更新SQL Server 2005中的XML w / out节点导致空错误

时间:2011-12-07 00:29:10

标签: sql-server xml sql-server-2005 sqlxml

所以我有一个脚本来更新/插入以下Node的XML值为True:

<Submitted>False</Submitted>

问题不是所有行都包含Node,因此会抛出错误:“@temp”上的“Mutator'vod()'无法在空值上调用。”

我需要做些什么来过滤掉XML中不包含“已提交”节点的行?

**注意,我有所有这些疯狂的CASTS,因为列类型是TEXT并且无法更改,因为客户端最初设置它。

DECLARE @temp XML

SELECT 
     @temp = CAST(CAST(TicorOregon..tbl_Module_RequestForms_Items.XML AS NTEXT) AS XML) 
FROM 
     TicorOregon..tbl_Module_RequestForms_Items
WHERE
 CAST(CAST(TicorOregon..tbl_Module_RequestForms_Items.XML AS NTEXT) AS XML).value('(//Record/Submitted)[1]', 'NVARCHAR(max)') <> 'True'

-- modification to local XML var
SET 
   @temp.modify('replace value of (//Record/Submitted[1]/text())[1] with "True"') 

-- write it back into the table as TEXT column      
UPDATE 
   TicorOregon..tbl_Module_RequestForms_Items
SET 
   XML = CAST(CAST(@temp AS VARCHAR(MAX)) AS TEXT)
WHERE
 CAST(CAST(TicorOregon..tbl_Module_RequestForms_Items.XML AS NTEXT) AS XML).value('(//Record/Submitted)[1]', 'NVARCHAR(max)') <> 'True'
AND  CAST(CAST(TicorOregon..tbl_Module_RequestForms_Items.XML AS NTEXT) AS XML).value('(//Record/Submitted)[1]', 'NVARCHAR(max)') <> null

1 个答案:

答案 0 :(得分:1)

在尝试更新之前测试您的XML变量是否为null。

if @temp is not null
begin
  -- modification to local XML var
  SET @temp.modify ----

  -- write it back into the table as TEXT column
  SET @temp.modify....
end

注意:如果有多行<Submitted>False</Submitted>,您可能会遇到此代码的问题。您将从@temp中的一行获取XML(可能是根据某个索引的最后一行),但您将使用该XML更新所有<Submitted>False</Submitted>