XQuery insert/update value - sql
I want to update xml like this one
<?xml version="1.0" encoding="utf-16"?>
<Properties xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<BackupPath>MyLocalPath</BackupPath>
</Properties>
using stored procedure
declare #PropertyName nvarchar(500)
declare #PropertyValue nvarchar(MAX)
set #PropertyName = 'BackupPath'
set #PropertyValue = 'MyTestPath'
DECLARE #ExistingSettings XML;
DECLARE #NewSettings nvarchar(MAX);
SET #ExistingSettings = (SELECT TOP(1) CAST(SettingsDefinition AS XML) FROM ApplicationSettings)
SET #ExistingSettings.modify('replace value of (/Properties/*[local-name() = sql:variable("#PropertyName")]/text())[1] with sql:variable("#PropertyValue")')
UPDATE ApplicationSettings
SET SettingsDefinition = CAST(#ExistingSettings AS nvarchar(MAX)), LastUpdate = GetDate()
WHERE ID = (SELECT TOP(1) ID FROM ApplicationSettings)
and this works fine as long as 'BackupPath' contains value
<BackupPath>MyLocalPath</BackupPath>
How to modify this query to insert value (or validate if needed) if
<BackupPath />
Just don't require a text node in your XPath.
SET #ExistingSettings.modify(
'replace value of (/Properties/' + #PropertyName + ')[1] with sql:variable("#PropertyValue")'
)
Related
SQL query variable nvarchar(max) can not store more than 4000 characters
I am having problem with dynamic sql query. Declare sql query variable with nvarchar(max) and building dynamic query and then running it with using sq_executesql. Please suggest if you have any solution for this. Below are my code snippet: DECLARE #count int, #sql nvarchar(max),#where nvarchar(max) SELECT #count = 2, #where=' Where 1 = 1 ' set #sql = ' SELECT top 2 ' + cast(#count as NVARCHAR) + ' as [Count], Name, 1 AS Column1,2 AS Column2,3 AS Column3,4 AS Column4,5 AS Column5,6 AS Column6,7 AS Column7,8 AS Column8,9 AS Column9,10 AS Column10,11 AS Column11,12 AS Column12,13 AS Column13,14 AS Column14,15 AS Column15,16 AS Column16,17 AS Column17,18 AS Column18,19 AS Column19,20 AS Column20,21 AS Column21,22 AS Column22,23 AS Column23,24 AS Column24,25 AS Column25,26 AS Column26,27 AS Column27,28 AS Column28,29 AS Column29,30 AS Column30,31 AS Column31,32 AS Column32,33 AS Column33,34 AS Column34,35 AS Column35,36 AS Column36,37 AS Column37,38 AS Column38,39 AS Column39,40 AS Column40,41 AS Column41,42 AS Column42,43 AS Column43,44 AS Column44,45 AS Column45,46 AS Column46,47 AS Column47,48 AS Column48,49 AS Column49,50 AS Column50,51 AS Column51,52 AS Column52,53 AS Column53,54 AS Column54,55 AS Column55,56 AS Column56,57 AS Column57,58 AS Column58,59 AS Column59,60 AS Column60,61 AS Column61,62 AS Column62,63 AS Column63,64 AS Column64,65 AS Column65,66 AS Column66,67 AS Column67,68 AS Column68,69 AS Column69,70 AS Column70,71 AS Column71,72 AS Column72,73 AS Column73,74 AS Column74,75 AS Column75,76 AS Column76,77 AS Column77,78 AS Column78,79 AS Column79,80 AS Column80,81 AS Column81,82 AS Column82,83 AS Column83,84 AS Column84,85 AS Column85,86 AS Column86,87 AS Column87,88 AS Column88,89 AS Column89,90 AS Column90,91 AS Column91,92 AS Column92,93 AS Column93,94 AS Column94,95 AS Column95,96 AS Column96,97 AS Column97,98 AS Column98,99 AS Column99,100 AS Column100,101 AS Column101,102 AS Column102,103 AS Column103,104 AS Column104,105 AS Column105,106 AS Column106,107 AS Column107,108 AS Column108,109 AS Column109,110 AS Column110,111 AS Column111,112 AS Column112,113 AS Column113,114 AS Column114,115 AS Column115,116 AS Column116,117 AS Column117,118 AS Column118,119 AS Column119,120 AS Column120,121 AS Column121,122 AS Column122,123 AS Column123,124 AS Column124,125 AS Column125,126 AS Column126,127 AS Column127,128 AS Column128,129 AS Column129,130 AS Column130,131 AS Column131,132 AS Column132,133 AS Column133,134 AS Column134,135 AS Column135,136 AS Column136,137 AS Column137,138 AS Column138,139 AS Column139,140 AS Column140,141 AS Column141,142 AS Column142,143 AS Column143,144 AS Column144,145 AS Column145,146 AS Column146,147 AS Column147,148 AS Column148,149 AS Column149,150 AS Column150,151 AS Column151,152 AS Column152,153 AS Column153,154 AS Column154,155 AS Column155,156 AS Column156,157 AS Column157,158 AS Column158,159 AS Column159,160 AS Column160,161 AS Column161,162 AS Column162,163 AS Column163,164 AS Column164,165 AS Column165,166 AS Column166,167 AS Column167,168 AS Column168,169 AS Column169,170 AS Column170,171 AS Column171,172 AS Column172,173 AS Column173,174 AS Column174,175 AS Column175,176 AS Column176,177 AS Column177,178 AS Column178,179 AS Column179,180 AS Column180,181 AS Column181,182 AS Column182,183 AS Column183,184 AS Column184,185 AS Column185,186 AS Column186,187 AS Column187,188 AS Column188,189 AS Column189,190 AS Column190,191 AS Column191,192 AS Column192,193 AS Column193,194 AS Column194,195 AS Column195,196 AS Column196,197 AS Column197,198 AS Column198,199 AS Column199,200 AS Column200,201 AS Column201,202 AS Column202,203 AS Column203,204 AS Column204,205 AS Column205,206 AS Column206,207 AS Column207,208 AS Column208,209 AS Column209,210 AS Column210,211 AS Column211,212 AS Column212,213 AS Column213,214 AS Column214,215 AS Column215,216 AS Column216,217 AS Column217,218 AS Column218,219 AS Column219,220 AS Column220,221 AS Column221,222 AS Column222,223 AS Column223,224 AS Column224,225 AS Column225,226 AS Column226,227 AS Column227,228 AS Column228,229 AS Column229,230 AS Column230,231 AS Column231,232 AS Column232,233 AS Column233,234 AS Column234,235 AS Column235,236 AS Column236,237 AS Column237,238 AS Column238,239 AS Column239,240 AS Column240,241 AS Column241,242 AS Column242,243 AS Column243,244 AS Column244,245 AS Column245,246 AS Column246,247 AS Column247,248 AS Column248,249 AS Column249,250 AS Column250,251 AS Column251,252 AS Column252,253 AS Column253,254 AS Column254,255 AS Column255,256 AS Column256,257 AS Column257,258 AS Column258,259 AS Column259,260 AS Column260 FROM Sys.Objects ' + #where + ' AND 2 = 2 ' SELECT LEN(#sql),#sql EXEC sp_executesql #sql
You need to explicit cast your large string to NVARCHAR(MAX) like this: DECLARE #count int, #sql nvarchar(max),#where nvarchar(max) SELECT #count = 2, #where=' Where 1 = 1 ' set #sql = ' SELECT top 2 ' + cast(#count as NVARCHAR) + CAST(' as [Count], Name, 1 AS Column1,2 AS Column2,3 AS Column3,4 AS Column4,5 AS Column5,6 AS Column6,7 AS Column7,8 AS Column8,9 AS Column9,10 AS Column10,11 AS Column11,12 AS Column12,13 AS Column13,14 AS Column14,15 AS Column15,16 AS Column16,17 AS Column17,18 AS Column18,19 AS Column19,20 AS Column20,21 AS Column21,22 AS Column22,23 AS Column23,24 AS Column24,25 AS Column25,26 AS Column26,27 AS Column27,28 AS Column28,29 AS Column29,30 AS Column30,31 AS Column31,32 AS Column32,33 AS Column33,34 AS Column34,35 AS Column35,36 AS Column36,37 AS Column37,38 AS Column38,39 AS Column39,40 AS Column40,41 AS Column41,42 AS Column42,43 AS Column43,44 AS Column44,45 AS Column45,46 AS Column46,47 AS Column47,48 AS Column48,49 AS Column49,50 AS Column50,51 AS Column51,52 AS Column52,53 AS Column53,54 AS Column54,55 AS Column55,56 AS Column56,57 AS Column57,58 AS Column58,59 AS Column59,60 AS Column60,61 AS Column61,62 AS Column62,63 AS Column63,64 AS Column64,65 AS Column65,66 AS Column66,67 AS Column67,68 AS Column68,69 AS Column69,70 AS Column70,71 AS Column71,72 AS Column72,73 AS Column73,74 AS Column74,75 AS Column75,76 AS Column76,77 AS Column77,78 AS Column78,79 AS Column79,80 AS Column80,81 AS Column81,82 AS Column82,83 AS Column83,84 AS Column84,85 AS Column85,86 AS Column86,87 AS Column87,88 AS Column88,89 AS Column89,90 AS Column90,91 AS Column91,92 AS Column92,93 AS Column93,94 AS Column94,95 AS Column95,96 AS Column96,97 AS Column97,98 AS Column98,99 AS Column99,100 AS Column100,101 AS Column101,102 AS Column102,103 AS Column103,104 AS Column104,105 AS Column105,106 AS Column106,107 AS Column107,108 AS Column108,109 AS Column109,110 AS Column110,111 AS Column111,112 AS Column112,113 AS Column113,114 AS Column114,115 AS Column115,116 AS Column116,117 AS Column117,118 AS Column118,119 AS Column119,120 AS Column120,121 AS Column121,122 AS Column122,123 AS Column123,124 AS Column124,125 AS Column125,126 AS Column126,127 AS Column127,128 AS Column128,129 AS Column129,130 AS Column130,131 AS Column131,132 AS Column132,133 AS Column133,134 AS Column134,135 AS Column135,136 AS Column136,137 AS Column137,138 AS Column138,139 AS Column139,140 AS Column140,141 AS Column141,142 AS Column142,143 AS Column143,144 AS Column144,145 AS Column145,146 AS Column146,147 AS Column147,148 AS Column148,149 AS Column149,150 AS Column150,151 AS Column151,152 AS Column152,153 AS Column153,154 AS Column154,155 AS Column155,156 AS Column156,157 AS Column157,158 AS Column158,159 AS Column159,160 AS Column160,161 AS Column161,162 AS Column162,163 AS Column163,164 AS Column164,165 AS Column165,166 AS Column166,167 AS Column167,168 AS Column168,169 AS Column169,170 AS Column170,171 AS Column171,172 AS Column172,173 AS Column173,174 AS Column174,175 AS Column175,176 AS Column176,177 AS Column177,178 AS Column178,179 AS Column179,180 AS Column180,181 AS Column181,182 AS Column182,183 AS Column183,184 AS Column184,185 AS Column185,186 AS Column186,187 AS Column187,188 AS Column188,189 AS Column189,190 AS Column190,191 AS Column191,192 AS Column192,193 AS Column193,194 AS Column194,195 AS Column195,196 AS Column196,197 AS Column197,198 AS Column198,199 AS Column199,200 AS Column200,201 AS Column201,202 AS Column202,203 AS Column203,204 AS Column204,205 AS Column205,206 AS Column206,207 AS Column207,208 AS Column208,209 AS Column209,210 AS Column210,211 AS Column211,212 AS Column212,213 AS Column213,214 AS Column214,215 AS Column215,216 AS Column216,217 AS Column217,218 AS Column218,219 AS Column219,220 AS Column220,221 AS Column221,222 AS Column222,223 AS Column223,224 AS Column224,225 AS Column225,226 AS Column226,227 AS Column227,228 AS Column228,229 AS Column229,230 AS Column230,231 AS Column231,232 AS Column232,233 AS Column233,234 AS Column234,235 AS Column235,236 AS Column236,237 AS Column237,238 AS Column238,239 AS Column239,240 AS Column240,241 AS Column241,242 AS Column242,243 AS Column243,244 AS Column244,245 AS Column245,246 AS Column246,247 AS Column247,248 AS Column248,249 AS Column249,250 AS Column250,251 AS Column251,252 AS Column252,253 AS Column253,254 AS Column254,255 AS Column255,256 AS Column256,257 AS Column257,258 AS Column258,259 AS Column259,260 AS Column260 FROM Sys.Objects ' AS NVARCHAR(MAX)) + #where + ' AND 2 = 2 ' SELECT LEN(#sql),#sql EXEC sp_executesql #sql When you are concatenating nvarchar(1-4000) strings the output string is not converted to max if it is not possible to store all the data. Also, in your example, you are concatenating a nvarchar value with the second large string which is varchar(4251). You can test what is the output parameter type very easy using sp_describe_first_result_set. So, we have: EXEC sp_describe_first_result_set #tsql = N'SELECT CAST(''a'' as nvarchar(50)) + cast(''b'' as varchar(4261)) as x' and the result is a string as follows: That's why we need to explicity convert the large string to NVARCHAR(MAX).
dc:creator from XML into SQL table
I am trying to store an XML file (Code below) but the the dc:creator is causing an error. I have found from other related questions on here stating that I should use ;WITH XMLNAMESPACES(''http://purl.org/dc/elements/1.1/'' AS dc) but this has not worked either any ideas on what might be the problem/solution ? . XML file: <?xml version="1.0" encoding="UTF-8"?> -<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:base="http://talksport.com/rss/sports-news/football/feed" version="2.0"> -<channel> <title>Football</title> <link>http://talksport.com/rss/sports-news/football/feed</link> <description/> <language>en</language> <atom:link type="application/rss+xml" rel="self" href="http://talksport.com/rss/sports-news/football/feed"/> -<item> <title>Hillsborough families 'back introduction of rail seating' as bereaved family says 'standing did not kill our 96'</title> <link>http://talksport.com/football/hillsborough-families-back-introduction-rail-seating-bereaved-family-says-standing-did-not</link> <description/> <pubDate>Wed, 19 Jul 2017 08:18:37 +0000</pubDate> <dc:creator>talkSPORT</dc:creator> <guid isPermaLink="false">247276 at http://talksport.com</guid> </item> </rss> This is the stored procedure: CREATE PROCEDURE feed.usp_importXML(#file VARCHAR(8000)) AS BEGIN DECLARE #Query VARCHAR(8000) SET #Query =' DECLARE #xmlFile as XML SET #xmlFile = ( cast SELECT CONVERT(XML,BulkColumn) as BulkColumn FROM OPENROWSET (BULK '''+#file+''', SINGLE_BLOB) AS t) INSERT INTO feed.tempXML (title,link,source) SELECT title = t.value (''title[1]'', ''NVARCHAR(300)''), link = t.value (''link[1]'', ''NVARCHAR(300)''), source = t.value(''(dc:creator)[1]'',''NVARCHAR(30)'') FROM #xmlFile.nodes(''/rss/channel/item'') AS xTable(t);' EXEC(#Query) END GO
In your case it might be enough to replace the dc: with a wildcard: *:. Assuming your XML is written into an XML file already, you might try as such: DECLARE #xmlFile XML= N'<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/" xml:base="http://talksport.com/rss/sports-news/football/feed" version="2.0"> <channel> <title>Football</title> <link>http://talksport.com/rss/sports-news/football/feed</link> <description /> <language>en</language> <atom:link type="application/rss+xml" rel="self" href="http://talksport.com/rss/sports-news/football/feed" /> <item> <title>Hillsborough families ''back introduction of rail seating'' as bereaved family says ''standing did not kill our 96''</title> <link>http://talksport.com/football/hillsborough-families-back-introduction-rail-seating-bereaved-family-says-standing-did-not</link> <description /> <pubDate>Wed, 19 Jul 2017 08:18:37 +0000</pubDate> <dc:creator>talkSPORT</dc:creator> <guid isPermaLink="false">247276 at http://talksport.com</guid> </item> </channel> </rss>'; SELECT title = t.value ('title[1]', 'NVARCHAR(300)'), link = t.value ('link[1]', 'NVARCHAR(300)'), source = t.value('(*:creator)[1]','NVARCHAR(30)') FROM #XmlFile.nodes('/rss/channel/item') AS xTable(t); This will work too: WITH XMLNAMESPACES('http://purl.org/dc/elements/1.1/' AS dc) SELECT title = t.value ('title[1]', 'NVARCHAR(300)'), link = t.value ('link[1]', 'NVARCHAR(300)'), source = t.value('(dc:creator)[1]','NVARCHAR(30)') FROM #XmlFile.nodes('/rss/channel/item') AS xTable(t); And you can declare the namespace within .value too: SELECT title = t.value ('title[1]', 'NVARCHAR(300)'), link = t.value ('link[1]', 'NVARCHAR(300)'), source = t.value('declare namespace dc="http://purl.org/dc/elements/1.1/";(dc:creator)[1]','NVARCHAR(30)') FROM #XmlFile.nodes('/rss/channel/item') AS xTable(t);
how to bypass the 65535 character limit in a select statement using "FOR XML"
I am aware of the 65535 truncation for text datatypes (and Varchar(MAX) as well). I am also aware of XML outputs that can be set to unlimited. I have a table that stores XML strings in a varchar(MAX) column called GEOM. My problem is that the xml snippet held in the geom column can exceed 65535 characters. I figure since it's XML, and I'm creating an XML output in my code anyways, why not just build the xml and send that out as such, since I can set XML output to "Unlimited". USE [buyerhero] GO /****** Object: StoredProcedure [dbo].[GEOIDKMLCOUNTY] Script Date: 9/17/2015 11:18:55 AM ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[GEOIDKMLCOUNTY] #CountyID nvarchar(30) AS DECLARE #kml XML DECLARE #kmlout NVARCHAR(MAX) SELECT #kml = CAST('<?xml version="1.0" encoding="utf-16" ?>' + '<kml xmlns="http://www.opengis.net/kml/2.2">' + '<Document>' + ' <Style id="Licensed"> <LineStyle> <color>ff000000</color> <width>2</width> </LineStyle> <PolyStyle> <color>1e1400FF</color> <fill>1</fill> <outline>1</outline> </PolyStyle> </Style> <Style id="NotLicensed"> <LineStyle> <color>ff000000</color> <width>2</width> </LineStyle> <PolyStyle> <color>1e14F0FF</color> <fill>1</fill> <outline>1</outline> </PolyStyle> </Style> <Style id="Other"> <LineStyle> <color>ff000000</color> <width>2</width> </LineStyle> <PolyStyle> <color>1e007800</color> <fill>1</fill> <outline>1</outline> </PolyStyle> </Style>' + ( select '<![CDATA[{"County":"' + r.CountyName + ', ' + r.State + '", "GEOID": "'+t.GEOID+'"}]]>' as Name, case t.IsLicensed when 2 then '#Licensed' when 1 then '#NotLicensed' else '#Other' end as StyleURL, cast(replace(geom,'"','') as xml) as Geometry from Tracts t join census_county_ref c on t.GEOID = c.GEOID join FIPSCountyCode r on c.STATEFP = r.StateANSI and c.COUNTYFP = r.CountyANSI where r.CountyID = #CountyID FOR XML PATH(''), ELEMENTS) + '</Document></kml>' AS XML) -- -- Perform replacement of < and > with < and > respectively -- SET #kmlout = REPLACE(REPLACE(CAST(#kml AS NVARCHAR(MAX)), '<', '<'), '>', '>') SET #kmlout = REPLACE(#kmlout, 'utf-16', 'utf-8') -- -- Return kmlout -- SELECT #kmlout in spite of the idea the geom columns is xml and I'm using cast(replace(geom,'"','') as xml) which is varchar(max), that field still gets truncated. How do I "untruncate" the field so I can output the XML? Thanks.
Use the concat function instead the + operator. the plus operator is limited to 8000 bytes. SELECT #kml =CAST(concat('your xml', the select,'the other xml')
XML query error in SQL Server 2005
For updating a mass records, I used xml query. From the front end (C#.net) I populate xml and pass it to a stored procedure as a parameter (like #Master_rows_xml_Update). I face a situation.. when I go for this command in the stored procedure declare #i INTEGER,#Master_rows_xml_Update XML; SET #Master_rows_xml_Update= '<root> <row Id="1" FinYearId="5" EmployeeId="55" EnteredOn="7/1/2011 12:00:00 AM" EnteredBy="1" HouseRentPaid="False" HouseRentAmount="3500.00" officeId="9"/> <row Id="2" FinYearId="5" EmployeeId="55" EnteredOn="7/1/2011 12:00:00 AM" EnteredBy="1" HouseRentPaid="False" HouseRentAmount="3500.00" officeId="9"/> </root>'; exec sp_xml_preparedocument #i output, #Master_rows_xml_Update; update EmployeeFinYearInvestment set EmployeeFinYearInvestment.FinYearId = ox.FinYearId, EmployeeFinYearInvestment.EmployeeId = ox.EmployeeId, EmployeeFinYearInvestment.EnteredOn = ox.EnteredOn, EmployeeFinYearInvestment.EnteredBy = ox.EnteredBy, EmployeeFinYearInvestment.HouseRentPaid = ox.HouseRentPaid, EmployeeFinYearInvestment.HouseRentAmount = ox.HouseRentAmount, EmployeeFinYearInvestment.officeId=ox.officeId from OpenXml(#i, 'root/row') with (Id INT,FinYearId INT, EmployeeId INT,EnteredOn DATETIME,EnteredBy INT , HouseRentPaid BIT,HouseRentAmount DECIMAL ,officeId INT ) ox where EmployeeFinYearInvestment.Id = ox.Id; exec sp_xml_removedocument #i; ..IT CAN NOT UPDATE ACTION TO FOLLOWING TABLE... Procedure also not returning any error... ANY IDEA... Thanks.. Anirban
I would try to get rid of OpenXml and those function - use the new XQuery/XPath stuff in SQL Server 2005 ! Try this - this should give you the values from your XML: DECLARE #XmlUpdate XML SET #XmlUpdate = '<root> <row Id="1" FinYearId="5" EmployeeId="55" EnteredOn="7/1/2011 12:00:00 AM" EnteredBy="1" HouseRentPaid="False" HouseRentAmount="3500.00" officeId="9"/> <row Id="2" FinYearId="5" EmployeeId="55" EnteredOn="7/1/2011 12:00:00 AM" EnteredBy="1" HouseRentPaid="False" HouseRentAmount="3500.00" officeId="9"/> </root>'; SELECT UpdRow.value('(#Id)[1]', 'int') AS 'ID', UpdRow.value('(#FinYearId)[1]', 'int') AS 'FinYearID', UpdRow.value('(#EmployeeId)[1]', 'int') AS 'EmployeeID', UpdRow.value('(#EnteredOn)[1]', 'datetime') AS 'EnteredOn', UpdRow.value('(#EnteredBy)[1]', 'int') AS 'EnteredBy', UpdRow.value('(#HouseRentPaid)[1]', 'bit') AS 'RentPaid', UpdRow.value('(#HouseRentAmount)[1]', 'decimal(20,4)') AS 'RentAmount', UpdRow.value('(#OfficeId)[1]', 'int') AS 'OfficeID' FROM #XmlUpdate.nodes('/root/row') AS R(UpdRow) And of course, if you can select it, you can also use it to update! UPDATE dbo.EmployeeFinYearInvestment SET EmployeeFinYearInvestment.FinYearId = UpdRow.value('(#FinYearId)[1]', 'int'), EmployeeFinYearInvestment.EmployeeId = UpdRow.value('(#EmployeeId)[1]', 'int'), ..... (and so on). ...... EmployeeFinYearInvestment.EnteredOn = ox.EnteredOn, FROM #XmlUpdate.nodes('/root/row') AS R(UpdRow) WHERE EmployeeFinYearInvestment.Id = UpdRow.value('(#Id)[1]', 'int');
Modify several xml attributes, based on a list
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
You can't use a variable as an argument to the xml-functions but you can use variables (and table columns) in the literal expression. I guess this does what you want. At least it should give you an idea of what you can do. declare #xmlData xml set #xmlData = '<something> <xxx id="1"/> <xxx id="2" runat="server" /> <xxx id="3"/> <yyy id="3" /> <zzz id="1"/> </something>' declare #tags table ( id int identity(1,1) primary key, tag varchar(25) ) insert into #tags select 'xxx' union select 'yyy' declare #tag varchar(25) declare #id int select top 1 #id = id, #tag = tag from #tags order by id while ##rowcount > 0 begin while #xmlData.exist('descendant::*[local-name() = sql:variable("#tag") and not(#runat)]') = 1 begin set #xmlData.modify('insert attribute runat { "server" } into descendant::*[local-name() = sql:variable("#tag") and not(#runat)][1]'); end select top 1 #id = id, #tag = tag from #tags where id > #id order by id end select #xmlData Result: <something> <xxx id="1" runat="server" /> <xxx id="2" runat="server" /> <xxx id="3" runat="server" /> <yyy id="3" runat="server" /> <zzz id="1" /> </something>