针对于 SQL Server 中的 XML 列,如何删除其中的一个 XML 节点呢?这里有两种方法。
方法1 直接通过SQL语句将目标节点设置为 null即可,直截了当,非常容易。
方法2 如下,查询后进行修改(相关操作我封装成了一个存储过程来演示,如下存储过程会从不同位置读取数据,并通过游标寻找并处理由 Guid 格式标明的目标数据)
IF( Object_id('proc_ClearSomeInformation', 'p') IS NOT NULL ) DROP PROC proc_ClearSomeInformation GO CREATE PROCEDURE proc_ClearSomeInformation( @sourceTable nvarchar(max), @identity nvarchar(max)) AS DECLARE @metadata xml IF @sourceTable = 'SourceA' SET @metadata = (SELECT MetadataSet FROM SourceA WHERE Id = @identity) ELSE SET @metadata = (SELECT MetadataSet FROM SourceB WHERE Id = @identity) DECLARE @mssql nvarchar(max) DECLARE @result xml -- Start to reset the metadata XML value DECLARE @columnName nvarchar(max) DECLARE traversalMetadataName CURSOR FAST_FORWARD FOR -- Get all metadata columns and traver them. SELECT name FROM syscolumns WHERE (id = (SELECT id FROM sysobjects WHERE (name = @sourceTable))) AND name like 'M[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]_%' -- GUID Format OPEN traversalMetadataName FETCH NEXT FROM traversalMetadataName INTO @columnName WHILE @@fetch_status = 0 BEGIN SET @mssql = N'SET @metadata.modify(''delete (/' + @columnName + ')[1]'')' EXEC sp_executesql @mssql, N'@metadata xml OUT', @metadata OUT FETCH NEXT FROM traversalMetadataName INTO @columnName END CLOSE traversalMetadataName DEALLOCATE traversalMetadataName SET @mssql = N'UPDATE ' + @sourceTable + ' SET MetadataSet = @metadata WHERE Id = ''' + @identity + '''' EXEC sp_executesql @mssql, N'@metadata xml', @metadata GO