Link to home
Start Free TrialLog in
Avatar of Larry Brister
Larry BristerFlag for United States of America

asked on

Select REPLACE in XML

I'm not sure if this is do-able.

I'm doing a select on a result set that is XML data.
select replace([theDate], 'images1', 'images') from theTemp

I need to do it with a replace statement and am getting
Argument data type xml is invalid for argument 1 of replace function.
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

http://technet.microsoft.com/en-us/library/ms345122.aspx#sql2k5_xqueryintro_topic13

See the above.  You will need to use XML methods like XQuery example in link like:
[theDate].replace(...)

Hope this helps.
Avatar of Larry Brister

ASKER

mwvisa1:,
  I am way out of my depth here.  You have a select statement example?
For XQuery or XML methods you may as well be speeking ancient Aramaic to me.
Sorry about that.  I needed a little more coffee in me anyway.  Out west right now, so been up early in this time zone. :)

Do something like this function:
(maybe there is another way, but with the method I suggested it doesn't like mutating the XML right in the select as it uses a SET command; therefore, I first create the below in code snippet then usage is as below)

SELECT dbo.fn_ChangeXMLText(theData, 'images1', 'images')
FROM theTemp
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE FUNCTION [dbo].[fn_ChangeXMLText]
(
	@theXml XML,
    @oldText nvarchar(50),
    @newText nvarchar(50)
)
RETURNS XML
AS
BEGIN
	SET @theXml.modify('replace value of (//text()[.=sql:variable("@oldText")])[1] with sql:variable("@newText")')
	RETURN @theXml
END

Open in new window

mwvisa1:
I set up some variables and ran it below.  No replace is taking place.

----CODE----
declare @theXml xml
declare @oldText nvarchar(50)
declare @newText nvarchar(50)
set @theXML = '<images1>http://www.mydomain.com/luxury_real_estate/florida/broward/fort_lauderdale/images/F868140_01.jpg</images1>'
set @oldText = 'images1'
set @newText = 'images'
SELECT dbo.fn_ChangeXMLText(@theXML, @oldText, @newText)
FROM theTemp


----RESULT SET-----
<images1>http://www.mydomain.com/luxury_real_estate/florida/broward/fort_lauderdale/images/F868140_01.jpg</images1>
images1 is a node in your example and not text.  I am trapping on text.  If you want to replace nodes, change the function to be //images1.
So...???
SET @theXml.modify('replace value of (//images1()[.=sql:variable("@oldText")])[1] with sql:variable("@newText")')
      RETURN @theXml
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You put me on the right track.  Will post final code later