SQL Variable in XML Node - sql

I have the following code:
DECLARE #x TABLE (item XML (document Galeries))
DECLARE #schemaname VARCHAR(100)
SET #schemaname = 'GaleriesSchem2'
INSERT into #x
SELECT '
<GaleriesSchem2>
<Image_1 OriginalName="Image">4814111.jpg</Image_1>
<Image_2 OriginalName="Image2">481411.jpg</Image_2>
</GaleriesSchem2>'
SELECT rref.value('.', 'varchar(MAX)') AS 'Value'
FROM #x
CROSS APPLY
item.nodes('//GaleriesSchem2/node()') AS Results(rref)
result:
1 | 4814111.jpg
2 | 481411.jpg
But I want to change the root element dynamically, for example:
item.nodes('//[local-name()=sql:variable("#schemaname")]/node()') AS Results(rref)
But this code doesn't work.

Use asterisk instead of double slash
DECLARE #x TABLE(item XML)
DECLARE #schemaname VARCHAR(100)
SET #schemaname = 'GaleriesSchem3'
INSERT into #x
SELECT '
<GaleriesSchem2>
<Image_1 OriginalName="Image">4814111.jpg</Image_1>
<Image_2 OriginalName="Image2">481411.jpg</Image_2>
</GaleriesSchem2>
<GaleriesSchem3>
<Image_1 OriginalName="Image">4814111_3.jpg</Image_1>
<Image_2 OriginalName="Image2">481411_3.jpg</Image_2>
</GaleriesSchem3>
'
SELECT rref.value('.', 'varchar(MAX)') AS 'Value'
FROM #x
CROSS APPLY
item.nodes('*[local-name()=sql:variable("#schemaname")]/node()') AS Results(rref)
See demo on SQLFiddle

Related

SQL Set/Declare Variable

I set my
declare #area as varchar(500)
set #area = '''Area1'',''Area2'''
I tried to put it in WHERE clause, but it doesn't detect area. I am guessing there is something wrong with set #area =?
This is what I'm trying to bring it in:
where area in (#area)
Please help, thanks.
Since you've got a list of elements to compare against, use a table variable to accumulate the comparison data, e.g.:
DECLARE #area as TABLE(Name VARCHAR(50));
INSERT INTO #area(Name) VALUES ('Area1'), ('Area2');
You can then use this either:
SELECT *
FROM MyTable
WHERE MyCol in (SELECT Name FROM #Area);
Or better, via a direct join (failed joins will be eliminated):
SELECT *
FROM MyTable INNER JOIN #Area
ON MyTable.MyCol = #Area.Name;
It should be a set rather then varchar variable:
where area in (select a from(values('Area1'),('Area2')) t(a))
Try something like
declare #area as varchar(500)
set #area = 'Area1,Area2'
SELECT *
FROM TableName
where area in (
SELECT Split.a.value('.', 'VARCHAR(100)') AS Area
FROM (SELECT CAST ('<M>' + REPLACE(#area, ',', '</M><M>')
+ '</M>' AS XML) AS String ) AS A
CROSS APPLY String.nodes ('/M') AS Split(a)
)
try use dynamic sql like-
declare #area as varchar(500)
set #area = 'Area1,Area2'
DECLARE #sql varchar(500)
set #sql='SELECT *
FROM [dbo].[tbl] AS t
WHERE area in ('+#area+')'
exec (#sql)
or
declare #area as varchar(500)
set #area = '''Area1'',''Area2'''
DECLARE #sql varchar(500)
set #sql='SELECT *
FROM [dbo].[tbl] AS t
WHERE area in ('+#area+')'
PRINT #sql
exec (#sql)
Result of your code
Query
declare #area as varchar(500)
set #area = '''Area1'',''Area2'''
Enter
print 'where area in (' + #area + ')'
Result
where area in ('Area1','Area2')

Replace " with &quote from varchar variable in sql

I'm trying to replace " with &quot, replace(#variable,'"','"') didn't help, in XML I got
<tag>&amp quot;Test&amp quot;</tag>
instead of
<tag>"test"</tag>
Example:
DECLARE #Text varchar(20) = '"Test"'
SET #Text = REPLACE(#Text,'"','&quot ;')
SELECT #Text
DECLARE #Table table (ID int)
INSERT INTO #Table
(ID)
VALUES
(123)
DECLARE #TestXml AS XML = (
SELECT
#Text
FROM #Table AS tag
FOR XML AUTO, ELEMENTS
)
SELECT #TestXml
Thanks in advance
if the problem is in the select query, try below sql
change the
SELECT #TestXml
to
SELECT '<tag>' + #TestXml.value('/tag[1]','varchar(max)') + '</tag>' as 'Word'
you will get below result in the select query:
Word
-------------------------------
<tag>"Test"</tag>
Update
to keep the '&' char we need the <![CDATA[...]>
try below sql
Declare #text nvarchar(20) = '"Test"'
select #text = replace(#text,'"','"')
Declare #table table (ID int)
Declare #xml as nvarchar(Max)
insert into #table values (123)
set #xml=( Select
1 as tag,
Null as Parent,
#text as [tag!1!!CDATA]
from #table
for xml Explicit
)
select #xml
Result:
result
---------------------------------------
<tag><![CDATA["Test"]]></tag>

Convert a column value into series of rows and columns in SQL [duplicate]

This question already has answers here:
Parsing a string SQL
(3 answers)
Closed 8 years ago.
I have a table in which one column is having data like as below:
column value='A,B,C,D,E,F
XA123,Name1,10/20,1.11,27-03-2014,414BJE
XA154,Name2,10/10,1.143,26-03-2014,414B32
XA134,Name21,10/50,1.123,27-03-2014,414B534E
XA125,Name32,20/20,1.1234,17-02-2014,414BJ3
XA124,Name43,30/20,1.165,23-02-2014,414B432
XA1256,Name324,50/60,4.31,07-01-2014,4GHH
XA1252,Name32,70/60,6.61,09-12-2013,414B2E'
Now i need this column value to be sorted out like that in a separate table.
Expected Output:
A B C D E F
XA123 Name1 10/20 1.11 27-03-2014 414BJE
XA154 Name2 10/10 1.143 26-03-2014 414B32
XA134 Name21 10/50 1.123 27-03-2014 414B534E
XA125 Name32 20/20 1.1234 17-02-2014 414BJ3
XA124 Name43 30/20 1.165 23-02-2014 414B432
XA1256 Name324 50/60 4.31 07-01-2014 4GHH
XA1252 Name32 70/60 6.61 09-12-2013 414B2E
Edit:
To get the above solution, at first, i divided column value based on new line character and inserted into a new table variable:
Declare #value nvarchar(max) ='A,B,C,D,E,F
XA123,Name1,10/20,1.11,27-03-2014,414BJE
XA154,Name2,10/10,1.143,26-03-2014,414B32
XA134,Name21,10/50,1.123,27-03-2014,414B534E
XA125,Name32,20/20,1.1234,17-02-2014,414BJ3
XA124,Name43,30/20,1.165,23-02-2014,414B432
XA1256,Name324,50/60,4.31,07-01-2014,4GHH
XA1252,Name32,70/60,6.61,09-12-2013,414B2E'
Declare #t Table
(
Id int identity(1,1),
Val VARCHAR(max)
)
while (charindex(char(13),#value)>0)
BEGIN
insert into #t (Val)
select substring(#value,1,charindex(char(13),#value))
set #value = (select substring(#value,charindex(char(13),#value)+1,len(#value)))
END
select * from #t
Then i created a new table variable and separated value for each row of #t table variable based on ','. Now hoping to get a generic and better solution.
Edited again:
Here I am trying to make a generic solution for this issue..lets say values in these rows can go to any number, for ex:
A,B,C,D,E,F could be
A,B,C,D,E,F,G
A,B,C,D,E,F,G,H
A,B,C,D,E,F,G,H....Z
so i am trying to get solution using dynamic query in below code, but getting an error: Must declare the scalar variable "#xml"
Declare #value nvarchar(max) ='A,B,C,D,E,F,G
XA123,Name1,10/20,1.11,27-03-2014,414BJE,afs
XA154,Name2,10/10,1.143,26-03-2014,414B32,ag
XA134,Name21,10/50,1.123,27-03-2014,414B534E,GSF
XA125,Name32,20/20,1.1234,17-02-2014,414BJ3,GG
XA124,Name43,30/20,1.165,23-02-2014,414B432,GS
XA1256,Name324,50/60,4.31,07-01-2014,4GHH,GS
XA1252,Name32,70/60,6.61,09-12-2013,414B2E,sg'
declare #query varchar(max)
declare #xml xml
declare #count int
declare #i int = 1
select #xml = '<item><value>'+replace(replace(#value, ',','</value><value>'), char(10),'</value></item><item><value>')+'</value></item>'
DECLARE #XmlTable TABLE (XmlResult XML)
INSERT INTO #XmlTable select #xml
set #count = (SELECT XmlResult.value('count(/item/value)', 'int')/XmlResult.value('count(/item)', 'int') FROM #XmlTable)
SET #query = 'select '
WHILE (#i <= #count)
BEGIN
IF(#i!=1)
BEGIN
set #query = #query + ', '
END
set #query = #query + 'N.value(''substring(value['+ cast(#i as varchar) +'],1)'',''varchar(10)'')'
SET #i = #i + 1
END
set #query = #query + ' from ' + '#xml.nodes' + '(''item'') as T(N)'
-- select #query
EXEC(#query)
Guys, any suggestion...
Here it is...
Declare #value nvarchar(max) ='A,B,C,D,E,F
XA123,Name1,10/20,1.11,27-03-2014,414BJE
XA154,Name2,10/10,1.143,26-03-2014,414B32
XA134,Name21,10/50,1.123,27-03-2014,414B534E
XA125,Name32,20/20,1.1234,17-02-2014,414BJ3
XA124,Name43,30/20,1.165,23-02-2014,414B432
XA1256,Name324,50/60,4.31,07-01-2014,4GHH
XA1252,Name32,70/60,6.61,09-12-2013,414B2E'
declare #xml xml
select #xml = '<item><value>'+replace(replace(#value, ',','</value><value>'), char(13),'</value></item><item><value>')+'</value></item>'
select
N.value('substring(value[1],1)', 'varchar(10)') as V1,
N.value('substring(value[2],1)', 'varchar(10)') as V2,
N.value('substring(value[3],1)', 'varchar(10)') as V3,
N.value('substring(value[4],1)', 'varchar(10)') as V4,
N.value('substring(value[5],1)', 'varchar(10)') as V5,
N.value('substring(value[6],1)', 'varchar(10)') as V6
from #xml.nodes('item') as T(N)
Try this, First Create a Scalar function AS
Create FUNCTION [dbo].[funcSplit_OneVal]
(
#param NVARCHAR(MAX),
#delimiter CHAR(1),
#nThVal int
)
RETURNS varchar(50)
--select dbo.funcSplit_OneVal('1,2,3,4',',',5)
AS
BEGIN
Declare #t TABLE (val NVARCHAR(MAX))
Declare #retVal varchar(50) = ''
SET #param += #delimiter
;WITH a AS
(
SELECT CAST(1 AS BIGINT) f,
CHARINDEX(#delimiter, #param) t,
1 seq
UNION ALL
SELECT t + 1,
CHARINDEX(#delimiter, #param, t + 1),
seq + 1
FROM a
WHERE CHARINDEX(#delimiter, #param, t + 1) > 0
)
INSERT #t
SELECT SUBSTRING(#param, f, t - f)
FROM a
OPTION(MAXRECURSION 0)
select top (#nThVal) #retVal =val from #t
RETURN #retVal
END
Then Execute following Script,
Declare #value nvarchar(max) ='A,B,C,D,E,F
XA123,Name1,10/20,1.11,27-03-2014,414BJE
XA154,Name2,10/10,1.143,26-03-2014,414B32
XA134,Name21,10/50,1.123,27-03-2014,414B534E
XA125,Name32,20/20,1.1234,17-02-2014,414BJ3
XA124,Name43,30/20,1.165,23-02-2014,414B432
XA1256,Name324,50/60,4.31,07-01-2014,4GHH
XA1252,Name32,70/60,6.61,09-12-2013,414B2E'
DECLARE #xml AS XML = CAST(('<X>'+REPLACE(#value,' ' ,'</X><X>')+'</X>') AS XML)
;With CTE as
(
SELECT C.value('.', 'varchar(250)') AS value
FROM #xml.nodes('X') as X(C)
)
select dbo.funcSplit_OneVal(value,',',1)
,dbo.funcSplit_OneVal(value,',',2)
,dbo.funcSplit_OneVal(value,',',3)
,dbo.funcSplit_OneVal(value,',',4)
,dbo.funcSplit_OneVal(value,',',5)
,dbo.funcSplit_OneVal(value,',',6)
from CTE
where len(value) > 0
If required then you can remove 'A,B,C... from variable & give alise in Last Select.

How to convert comma separated NVARCHAR to table records in SQL Server 2005?

I have a list of ids separated by comma like:
1,17,25,44,46,67,88
I want to convert them to a table records ( into a temporary table ) like
#tempTable
number_
--------
1
17
25
44
46
67
88
It is possible with a function, a table-valued one ?
Why I want this ? I want to use for INNER JOIN clause (into stored procedure) with another table(s) like as:
SELECT a,b,c FROM T1
INNER JOIN functionNameWhichReturnsTable
ON functionNameWhichReturnsTable.number_ = T1.a
I cannot use IN because I will use stored procedure which accepts a parameter of type NVARCHAR. That parameter will provide the list of ids.
Thank you
Possible duplicate of separate comma separated values and store in table in sql server.
Please try a precise one from Comma-Delimited Value to Table:
CREATE FUNCTION [dbo].[ufn_CSVToTable] ( #StringInput VARCHAR(8000), #Delimiter nvarchar(1))
RETURNS #OutputTable TABLE ( [String] VARCHAR(10) )
AS
BEGIN
DECLARE #String VARCHAR(10)
WHILE LEN(#StringInput) > 0
BEGIN
SET #String = LEFT(#StringInput,
ISNULL(NULLIF(CHARINDEX(#Delimiter, #StringInput) - 1, -1),
LEN(#StringInput)))
SET #StringInput = SUBSTRING(#StringInput,
ISNULL(NULLIF(CHARINDEX(#Delimiter, #StringInput), 0),
LEN(#StringInput)) + 1, LEN(#StringInput))
INSERT INTO #OutputTable ( [String] )
VALUES ( #String )
END
RETURN
END
GO
Check the requirement in other way using XML:
DECLARE #param NVARCHAR(MAX)
SET #param = '1:0,2:1,3:1,4:0'
SELECT
Split.a.value('.', 'VARCHAR(100)') AS CVS
FROM
(
SELECT CAST ('<M>' + REPLACE(#param, ',', '</M><M>') + '</M>' AS XML) AS CVS
) AS A CROSS APPLY CVS.nodes ('/M') AS Split(a)
Here's a trick that doesn't need a function or XML.
Basically the string gets transformed into a single insert statement for a temporary table.
The temp table can then be used for further processing.
IF OBJECT_ID('tempdb..#tmpNum') IS NOT NULL
DROP TABLE #tmpNum;
CREATE TABLE #tmpNum (num int);
DECLARE #TEXT varchar(max) = '1,17,25,44,46,67,88';
DECLARE #InsertStatement varchar(max);
SET #InsertStatement = 'insert into #tmpNum (num) values ('+REPLACE(#TEXT,',','),(')+');';
EXEC (#InsertStatement);
-- use the temp table
SELECT *
FROM YourTable t
WHERE t.id IN (SELECT DISTINCT num FROM #tmpNum);
This method is usable for up to 1000 values.
Because 1000 is the max limit of a row value expression.
Also, as Stuart Ainsworth pointed out.
Since this method uses Dynamic Sql, be wary of code injection and don't use it for strings based on user input.
Side-note
Starting from MS Sql Server 2016, one could simply use the STRING_SPLIT function.
DECLARE #TEXT varchar(max);
SET #TEXT = '1,17,25,44,46,67,88';
SELECT t.*
FROM YourTable t
JOIN (SELECT DISTINCT CAST(value AS INT) num FROM STRING_SPLIT(#TEXT, ',')) nums
ON t.id = nums.num;
Completing the answers, you could also use the CSV string to store multiple values in multiple columns:
--input sql text
declare #text_IN varchar(max) ='text1, text1.2, text1.3, 1, 2010-01-01\r\n text2, text2.2, text2.3, 2, 2016-01-01'
Split the csv file into rows:
declare #temptable table (csvRow varchar(max))
declare #DelimiterInit varchar(4) = '\r\n'
declare #Delimiter varchar(1) = '|'
declare #idx int
declare #slice varchar(max)
set #text_IN = REPLACE(#text_IN,#DelimiterInit,#Delimiter)
select #idx = 1
if len(#text_IN)<1 or #text_IN is null return
while #idx!= 0
begin
set #idx = charindex(#Delimiter,#text_IN)
if #idx!=0
set #slice = left(#text_IN,#idx - 1)
else
set #slice = #text_IN
if(len(#slice)>0)
insert into #temptable(csvRow) values(#slice)
set #text_IN = right(#text_IN,len(#text_IN) - #idx)
if len(#text_IN) = 0 break
end
Split rows into columns:
;WITH XMLTable (xmlTag)
AS
(
SELECT CONVERT(XML,'<CSV><champ>' + REPLACE(csvRow,',', '</champ><champ>') + '</champ></CSV>') AS xmlTag
FROM #temptable
)
SELECT RTRIM(LTRIM(xmlTag.value('/CSV[1]/champ[1]','varchar(max)'))) AS Column1,
RTRIM(LTRIM(xmlTag.value('/CSV[1]/champ[2]','varchar(max)'))) AS Column2,
RTRIM(LTRIM(xmlTag.value('/CSV[1]/champ[3]','varchar(max)'))) AS Column3,
RTRIM(LTRIM(xmlTag.value('/CSV[1]/champ[4]','int'))) AS Column4,
RTRIM(LTRIM(xmlTag.value('/CSV[1]/champ[5]','datetime'))) AS Column5
FROM XMLTable
The following works:
declare #parStoreNo As varchar(8000) = '1,2,3,4'
CREATE TABLE #parStoreNo (StoreNo INT)-- drop #parStoreNo
declare #temptable VARCHAR(1000) = #parStoreNo
declare #SQL VARCHAR(1000)
SELECT #SQL = CONVERT(VARCHAR(1000),' select ' + REPLACE(ISNULL(#temptable,' NULL '),',', ' AS Col UNION ALL SELECT '))
INSERT #parStoreNo (StoreNo)
EXEC (#SQL)
I am using XML Function as below...
DECLARE #str VARCHAR(4000) = '6,7,7,8,10,12,13,14,16,44,46,47,394,396,417,488,714,717,718,719,722,725,811,818,832,833,836,837,846,913,914,919,922,923,924,925,926,927,927,928,929,929,930,931,932,934,935,1029,1072,1187,1188,1192,1196,1197,1199,1199,1199,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1366,1367,1387,1388,1666,1759,1870,2042,2045,2163,2261,2374,2445,2550,2676,2879,2880,2881,2892,2893,2894'
Declare #x XML
select #x = cast('<A>'+ replace(#str,',','</A><A>')+ '</A>' as xml)
select t.value('.', 'int') as inVal
from #x.nodes('/A') as x(t)
I prefer this because not need to create any separate function and proc. Also I don't have to opt dynamic SQL query which I prefer most.
Convert Comma Separated String to Table
DECLARE #str VARCHAR(4000) = '6,7,7,8,10,12,13,14,16,44,46,47,394,396,417,488,714,717,718,719,722,725,811,818,832'
DECLARE #x XML
select #x = cast('<A>'+ replace(#str,',','</A><A>')+ '</A>' as xml)
select t.value('.', 'int') as inVal
from #x.nodes('/A') as x(t)
Try this code
SELECT RTRIM(part) as part
INTO Table_Name
FROM dbo.splitstring(#Your_Comma_string,',')
splitstring Function is as follows
CREATE FUNCTION dbo.splitstring ( #stringToSplit VARCHAR(MAX) )
RETURNS
#returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE #name NVARCHAR(255)
DECLARE #pos INT
WHILE CHARINDEX(',', #stringToSplit) > 0
BEGIN
SELECT #pos = CHARINDEX(',', #stringToSplit)
SELECT #name = SUBSTRING(#stringToSplit, 1, #pos-1)
INSERT INTO #returnList
SELECT #name
SELECT #stringToSplit = SUBSTRING(#stringToSplit, #pos+1, LEN(#stringToSplit)-#pos)
END
INSERT INTO #returnList
SELECT #stringToSplit
RETURN
END

SQL- fetch value from XML parent node (separately)

In my below Query it's return all the recode set as a XML into a single variable.But i need all the parent node values into separate while loop.Just run the below query:
---------Just Declare the temp Table -------------------------------------------------
IF OBJECT_ID('tempdb.dbo.##TestTable','U')IS NOT NULL DROP TABLE ##TestTable
CREATE TABLE ##TestTable(id int,Uname nvarchar(max),Uaddress nvarchar(max))
INSERT INTO ##TestTable values (1,'abc','NY')
INSERT INTO ##TestTable values (2,'def','WD')
INSERT INTO ##TestTable values (3,'','KL')
DECLARE #XML XML
DECLARE #WhereClause nvarchar(max)
DECLARE #CountVal int
SELECT #CountVal=count(*) from ##TestTable
SET #XML= (SELECT * FROM ##TestTable FOR XML PATH('ParentNode'), ELEMENTS XSINIL)
SELECT #XML
;with cte as
( select xr.value('fn:local-name(.)','nvarchar(max)') name, xr.value('.','nvarchar(max)') val from #xml.nodes('//.') xq(xr)
where xr.value('fn:local-name(.)','nvarchar(max)')<>''
)
SELECT #WhereClause= STUFF((select ' and ' + name + '='''+val+'''' from cte for xml path('')),1,4,'')
SELECT #WhereClause
WHILE (#CountVal>0)
BEGIN
SELECT #WhereClause
SET #CountVal=#CountVal-1
END
IF OBJECT_ID('tempdb.dbo.##TestTable','U')IS NOT NULL DROP TABLE ##TestTable
Current sample XML(in #XML):
<ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>1</id><Uname>abc</Uname><Uaddress>NY</Uaddress></ParentNode><ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>2</id><Uname>def</Uname><Uaddress>WD</Uaddress></ParentNode><ParentNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><id>3</id><Uname /><Uaddress>KL</Uaddress></ParentNode>
Current the output of #WhereClause is (all into in a single #WhereClause variable):
ParentNode='1abcNY' and id='1' and Uname='abc' and Uaddress='NY' and ParentNode='2defWD' and id='2' and Uname='def' and Uaddress='WD' and ParentNode='3KL' and id='3' and Uname='' and Uaddress='KL'
But my Expected output is:
Firstly(in #WhereClause): id='1' and Uname='abc' and Uaddress='NY'
Secondly(in #WhereClause):id='2' and Uname='def' and Uaddress='WD'
Thirdly(in #WhereClause):id='3' and Uname='' and Uaddress='KL'
.
.
How i get it. Thanks in advance.
Try this:
declare #WhereClause nvarchar(max)
declare #CountVal int
select #CountVal=count(*)
from ##TestTable
while #CountVal>0
begin
select #WhereClause =
(
select ' and '+T.N.value('local-name(.)', 'nvarchar(max)')+'='+T.N.value('.', 'nvarchar(max)')
from (
select *
from ##TestTable
where id = #CountVal
for xml path(''), type
) as C(X)
cross apply C.X.nodes('/*') as T(N)
for xml path(''), type
).value('substring((./text())[1], 6)', 'nvarchar(max)')
select #WhereClause
set #CountVal=#CountVal-1
end
seem to be late and having missunderstood, that woul habe been my approach
DECLARE #XML XML
DECLARE #WhereClause nvarchar(max)
DECLARE #CountVal int
SELECT #CountVal=count(*) from ##TestTable
SET #XML= (SELECT * FROM ##TestTable FOR XML PATH('ParentNode'), ELEMENTS XSINIL)
SELECT #XML
;with cte as
( select xr.value('fn:local-name(.)','nvarchar(max)') name, xr.value('.','nvarchar(max)') val from #xml.nodes('//.') xq(xr)
where xr.value('fn:local-name(.)','nvarchar(max)')<>'' and xr.value('fn:local-name(.)','nvarchar(max)')<>'ParentNode'
)
SELECT #WhereClause= SubString((select Case when Name ='id' then CHAR(10) +''+ name + '='''+val+'''' else ' and ' + name + '='''+val+'''' end from cte for xml path('')),2,100000000)
Print #WhereClause