From a previous post: SQL Server XML add attribute if non-existent
What I would like to do is be able to modify multiple tags. Below is the code that shows what I would like to do, but cannot, since I get the error: The argument 1 of the XML data type method "exist" must be a string literal. Is there a way to modify the XML using variables, rather than literals?
ALTER FUNCTION [dbo].[ConvertXmlData](@xmlData XML)
RETURNS XML
AS
BEGIN
DECLARE @tags TABLE (
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
TAG VARCHAR(25)
)
INSERT INTO @tags
SELECT 'xxx' UNION
SELECT 'yyy'
DECLARE @counter INT
DECLARE @count INT
DECLARE @id INT
DECLARE @tag VARCHAR(25)
DECLARE @exist VARCHAR(100)
DECLARE @insert VARCHAR(100)
DECLARE @existX VARCHAR(100)
DECLARE @insertX VARCHAR(100)
SET @exist = 'descendant::{0}[not(@runat)]'
SET @insert = 'insert attribute runat { "server" } into descendant::{0}[not(@runat)][1]'
SET @counter = 1
SELECT @count = COUNT(*) FROM @tags
WHILE @counter <= @count BEGIN
SELECT @tag = TAG FROM @tags WHERE ID = @counter
SET @existX = REPLACE(@existX, '[0]', @tag)
WHILE @xmlData.exist(@existX) = 1 BEGIN
SET @xmlData.modify(REPLACE(@insertX, '[0]', @tag));
END
SET @counter = @counter + 1
END
RETURN @xmlData
END