我的数据库中有一个xml结构,如下所示:
<ArrayOfContactDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ContactDetails id="93679d1d-9feb-45d1-8356-e85d188fa34c">
<contactid>93679d1d-9feb-45d1-8356-e85d188fa34c</contactid>
<contactname>Name 1</contactname>
<contactemail>Email 1</contactemail>
<contactphonenumber>123234234</contactphonenumber>
</ContactDetails>
<ContactDetails id="69f54067-edf9-414e-80b6-099ac471dc43">
<contactid>69f54067-edf9-414e-80b6-099ac471dc43</contactid>
<contactname>Name 2</contactname>
<contactemail>Email 2</contactemail>
<contactphonenumber>123234234</contactphonenumber>
</ContactDetails>
<ContactDetails id="93144086-be1c-4f34-a5f7-6e8ac67c2121">
<contactid>93144086-be1c-4f34-a5f7-6e8ac67c2121</contactid>
<contactname>Name 3</contactname>
<contactemail>Email 3</contactemail>
<contactphonenumber>123456</contactphonenumber>
</ContactDetails>
</ArrayOfContactDetails>
我正在尝试根据ContactDetails id属性删除ContactDetails节点。但我似乎陷入了困境。
我的SP代码是这样的
UPDATE tableName
SET tableField.modify('delete //ContactDetails[@id=sql:variable("@contactId")]')
WHERE tableId = @tableId
我在页面上没有错误或调试/执行sp时它只是让我疯了,为什么它不起作用!!
谢谢, 汤姆
答案 0 :(得分:8)
你的@contactID
变量定义为什么?
它适用于我的机器:-)试试这个:
DECLARE @work TABLE (ID INT NOT NULL, XmlContent XML)
INSERT INTO @work VALUES(1, '<ArrayOfContactDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ContactDetails id="93679d1d-9feb-45d1-8356-e85d188fa34c">
<contactid>93679d1d-9feb-45d1-8356-e85d188fa34c</contactid>
<contactname>Name 1</contactname>
<contactemail>Email 1</contactemail>
<contactphonenumber>123234234</contactphonenumber>
</ContactDetails>
<ContactDetails id="69f54067-edf9-414e-80b6-099ac471dc43">
<contactid>69f54067-edf9-414e-80b6-099ac471dc43</contactid>
<contactname>Name 2</contactname>
<contactemail>Email 2</contactemail>
<contactphonenumber>123234234</contactphonenumber>
</ContactDetails>
<ContactDetails id="93144086-be1c-4f34-a5f7-6e8ac67c2121">
<contactid>93144086-be1c-4f34-a5f7-6e8ac67c2121</contactid>
<contactname>Name 3</contactname>
<contactemail>Email 3</contactemail>
<contactphonenumber>123456</contactphonenumber>
</ContactDetails>
</ArrayOfContactDetails>')
DECLARE @contactID VARCHAR(50) = '69f54067-edf9-414e-80b6-099ac471dc43'
UPDATE @work
SET XmlContent.modify('delete //ContactDetails[@id=sql:variable("@contactId")]')
where id = 1
SELECT * FROM @Work WHERE id = 1
我得到的结果XML没有那个<ContactDetails>
节点。
您的@contactID
是否被定义为UNIQUEIDENTIFIER
?您必须将其转换为varchar
- XML操作内容全部使用字符串....
PS:我刚注意到的另一件事 - 这也不会起作用:
DECLARE @YourOriginalContactID UNIQUEIDENTIFIER
SET @YourOriginalContactID = '69f54067-edf9-414e-80b6-099ac471dc43'
DECLARE @ContactID VARCHAR(50)
SET @ContactID = CAST(@YourOriginalContactID AS VARCHAR(50))
这是失败的,因为CAST
操作将GUID转换为UPPERCASE字符串.....你需要再次将它变成小写:
SET @ContactID = LOWER(CAST(@YourOriginalContactID AS VARCHAR(50)))
然后再次有效!非常棘手....