Author |
Topic |
magmo
Aged Yak Warrior
558 Posts |
Posted - 2010-12-08 : 03:06:33
|
HiI have this piece of query that needs some tweaking....Declare @TheName Char(50)SET @TheName = 'sLine1'SELECT t.u.value('(sLine1/text())[1]', 'nvarchar(30)') as [Namnet], tbl.IDFROM tbl_Order tblCROSS APPLY XmlFormValues.nodes('/root')t(u) WHERE (tbl.ID = 18025) How can I replace the t.u.value('(sLine1 part with the @TheName? |
|
pk_bohra
Master Smack Fu Yak Hacker
1182 Posts |
Posted - 2010-12-08 : 03:42:56
|
One way is to use dynamic sql but it got its own pros and cons.http://www.sommarskog.se/dynamic_sql.html |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-12-08 : 03:51:46
|
Here is a quick way to do the search and absolutely no need for dynamic sql!DECLARE @Sample TABLE ( ID INT, XmlFormValues XML )INSERT @SampleSELECT 18025, N'<root><sLine1>Peso</sLine1><sLine2>Yak</sLine2><a><sLine1>MVP</sLine1></a></root>'DECLARE @theElement NVARCHAR(MAX)SET @theElement = 'sLine1'SELECT t.u.value('(text())[1]', 'NVARCHAR(30)') AS Namnet, tbl.IDFROM @Sample AS tblCROSS APPLY XmlFormValues.nodes('/root/* [local-name(.) = sql:variable("@theElement")]') AS t(u) WHERE tbl.ID = 18025 Notice that there are two <sLine1> elements (second is on another level). N 56°04'39.26"E 12°55'05.63" |
 |
|
magmo
Aged Yak Warrior
558 Posts |
Posted - 2010-12-08 : 05:38:04
|
Hi PesoIf I run your sample code it works just fine, but if I use this code...Declare @theElement Char(50)SET @theElement = 'sLine1'SELECT t.u.value('(text())[1]', 'NVARCHAR(30)') AS Namnet, tbl.IDFROM tbl_Order tblCROSS APPLY XmlFormValues.nodes('/root/* [local-name(.) = sql:variable("@theElement")]') AS t(u) WHERE tbl.ID = 18025 I don't get any errors, but I don't get any results either. Any ideas of what might ne wrong? |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-12-08 : 06:21:40
|
XML is case sensiTivE. Also, change the declaration of @theElement to VARCHAR(50). N 56°04'39.26"E 12°55'05.63" |
 |
|
magmo
Aged Yak Warrior
558 Posts |
Posted - 2010-12-08 : 06:29:31
|
Excellent, that did it. Thanks! |
 |
|
Sachin.Nand
2937 Posts |
Posted - 2010-12-08 : 06:38:48
|
Another way using Exists methodcreate table #t(id int,t xml)insert into #tselect 18025,N'<root><sLine1>Peso</sLine1><sLine2>Yak</sLine2><a><sLine1>MVP</sLine1></a></root>'DECLARE @value VARCHAR(20)SET @value ='MVP'if exists(Select #t.t.exist('/root/*[text()=sql:variable("@value")]')from #t) Select * from( Select id,x.i.value('.','varchar(20)')value from #t t1 cross apply t1.t.nodes('/root/*')x(i))T where value=@valuedrop table #t PBUH |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2010-12-08 : 06:40:39
|
quote: Originally posted by magmo Excellent, that did it. Thanks!
Varsågod! N 56°04'39.26"E 12°55'05.63" |
 |
|
|