I have a list of strings as:
List<string> list = new List<string>();
list.Add("912-123898493");
list.Add("021-36574864");
list.Add("021-36513264");
I want to convert it in XML and then send it as a parameter to Stored procedure, so that this could be read.
How to read this XML in sql server so that each and every string can be placed in different cell? Please help!!
It depends of what structure your xml will have.
Here's example of how you can read elements xml:
declare #Data xml
select #Data = '
<root>
<value>912-123898493</value>
<value>021-36574864</value>
<value>021-36513264</value>
</root>'
select T.C.value('data(.)', 'nvarchar(128)') as [Data]
from #Data.nodes('/root/value') as T(C)
Related
This might be a simple question for those who are experienced in working with JSON in SQL Server. I found this interesting way of aggregating strings using FOR XML in here.
create table #t (id int, name varchar(20))
insert into #t
values (1, 'Matt'), (1, 'Rocks'), (2, 'Stylus')
select id
,Names = stuff((select ', ' + name as [text()]
from #t xt
where xt.id = t.id
for xml path('')), 1, 2, '')
from #t t
group by id
How can I do the same using JSON instead of XML?
You cannot replace the XML approach with JSON. This string concatenation works due to some XML inner peculiarities, which are not the same in JSON.
Starting with SQL Server 2017 onwards you can use STRING_AGG(), but with earlier versions, the XML approach is the way to go.
Some background and a hint
First the hint: The code you showed is not safe for the XML special characters. Check my example below.
First I declare a simple XML
DECLARE #xml XML=
N'<a>
<b>1</b>
<b>2</b>
<b>3</b>
<c>
<d>x</d>
<d>y</d>
<d>z</d>
</c>
</a>';
--The XPath . tells the XML engine to use the current node (and all within)
--Therefore this will return any content within the XML
SELECT #xml.value('.','varchar(100)')
--You can specify the path to get 123 or xyz
SELECT #xml.query('/a/b').value('.','varchar(100)')
SELECT #xml.query('//d').value('.','varchar(100)')
Now your issue to concatenate tabular data:
DECLARE #tbl TABLE(SomeString VARCHAR(100));
INSERT INTO #tbl VALUES('This'),('will'),('concatenate'),('magically'),('Forbidden Characters & > <');
--The simple FOR XML query will tag the column with <SomeString> and each row with <row>:
SELECT SomeString FROM #tbl FOR XML PATH('row');
--But we can create the same without any tags:
--Attention: Look closely, that the result - even without tags - is XML typed and looks like a hyper link in SSMS.
SELECT SomeString AS [*] FROM #tbl FOR XML PATH('');
--Now we can use as a sub-select within a surrounding query.
--The result is returned as string, not XML typed anymore... Look at the forbidden chars!
SELECT
(SELECT SomeString FROM #tbl FOR XML PATH('row'))
,(SELECT SomeString AS [*] FROM #tbl FOR XML PATH(''))
--We can use ,TYPE to enforce the sub-select to be treated as XML typed itself
--This allows to use .query() and/or .value()
SELECT
(SELECT SomeString FROM #tbl FOR XML PATH('row'),TYPE).query('data(//SomeString)').value('.','nvarchar(max)')
,(SELECT SomeString AS [*] FROM #tbl FOR XML PATH(''),TYPE).value('.','nvarchar(max)')
XQuery's .data() can be used to concatenate named elements with blanks in between.
XQuery's .value() must be used to re-escpae forbidden characters.
I want to get a node 'RID' from this xml :
<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>
I am using the following query in SQL server 2012:
DECLARE #data xml
DECLARE #RID varchar(256)
select #data = CAST(CAST(Data AS text) AS XML) from message where index=1
select #data
SET #RID = #data.value('(/ReplicationStatus/RID)[1]', 'varchar(256)' )
SELECT #RID
Here, Data is ntext. I casted it twice from ntext to text and then to xml. Now, I am getting #data in xml format. But RID returned is always null. Can someone help me with this?
You could try after converting ntext data to xml :
DECLARE #DATA XML = '<ts:Status xmlns:ts="DistServices">
<RID>
5ec827e9-0429-4f5a-9d4b-16d3503ff07b
</RID>
<PIN>
5678
</PIN>
</ts:Status>'
SELECT
a.value('./RID[1]', 'NVARCHAR(MAX)') [RID],
a.value('./PIN[1]', 'NVARCHAR(MAX)') [PIN]
FROM #DATA.nodes ('*') as split(a)
Result :
RID PIN
5ec827e9-0429-4f5a-9d4b-16d3503ff07b 5678
Note :
IMPORTANT! ntext, text, and image data types will be removed in a future version of SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Read https://learn.microsoft.com/en-us/sql/t-sql/data-types/ntext-text-and-image-transact-sql
I have a SQL Server procedure written that exports data in XML format. In the database, I also have PDFs that have been stored as BLOB files that I need to export with the data. Is it possible to convert these to PDF as I export?
This is really easy...
I assume, that the BLOBs live in a table column of type VARBINARY(MAX). Including such a column into a SELECT ... FOR XML PATH will implicitly do the conversion for you.
In this example I use three tiny binary BLOBs, put them into a XML-variable and re-read them. There should be not difference with your PDF BLOBs:
DECLARE #tbl TABLE(ID INT,Content VARBINARY(MAX));
INSERT INTO #tbl VALUES
(1,0x101010101010101010101)
,(2,0x110011001100110011001100)
,(3,0x111000111000111000111000);
DECLARE #xml XML=
(
SELECT ID AS [#ID]
,Content
FROM #tbl
FOR XML PATH('myData'),ROOT('root')
);
SELECT #xml;
The result as XML (implicit conversion to base64)
<root>
<myData ID="1">
<Content>AQEBAQEBAQEBAQE=</Content>
</myData>
<myData ID="2">
<Content>EQARABEAEQARABEA</Content>
</myData>
<myData ID="3">
<Content>ERAAERAAERAAERAA</Content>
</myData>
</root>
Now I read the data from the XML
SELECT B.value('Content[1]','varbinary(max)') AS BackToVarbinary
FROM #xml.nodes('/root/myData') AS A(B)
The result
BackToVarbinary
0x0101010101010101010101
0x110011001100110011001100
0x111000111000111000111000
SELECT
**FIELDS**
AS [text()] --Stops the XMLPATH line rendering output as XML
FROM #temp
WHERE **CONDITIONS**
FOR XML PATH('')
This doesn't work in SQL server 2000 (unsupported).
I have tried using FOR XML RAW but it returns loads of useless information. i.e:
<row text x0028 x0029="blah, blah"> <row text x0028 x0029="blah">
The above code currently returns a concatenated string(made up of multiple columns of varying types) from every single row in the table.
How can I achieve this in SQL Server 2000?
Concatenation in SQL Server 2000:
declare #s varchar(8000);
set #s = '';
select #s = #s + field1 + field2 + field3
from #temp
where ...
order by ...;
select #s;
The XML datatype isn't supported in 2000, it was introduced in 2005.
SQL 2000 did introduce the FOR XML, but it only supported RAW, AUTO, and EXPLICIT
You've to define some text or character inside FOR XML PATH(' ') like,
FOR XML PATH('abc'). You can also use FOR XML RAW('abc') for outputting raw XML.
I need to update an XML document stored in a Microsoft SQL Server database, however the vendor of the product chose to store the XML in a TEXT column.
I've been able to extract the TEXT into an XML-type variable and perform the update I need on the xml within this variable, but when I try to UPDATE the column to push the change back to the database, I run into trouble.
Looking through the documentation it appears that it's not possible to simply CAST/CONVERT an XML type variable to insert it into a TEXT column, but I would think there is some way to extract the xml "string" from the XML-type variable and UPDATE the column using this value.
Any suggestions are appreciated, but I would like to keep the solution pure SQL that it can be run directly (no C# custom function, etc.); just to keep the impact on the database minimal.
(note: isn't it a bit absurd that you can't just CAST XML as TEXT? I'm just saying...)
Casting the XML as VARCHAR(MAX) works.
declare #xml xml
declare #tblTest table (
Id int,
XMLColumn text
)
insert into #tblTest
(Id, XMLColumn)
values
(1, '<MyTest><TestNode>A</TestNode></MyTest>')
set #xml = '<MyTest><TestNode>A</TestNode><TestNode>B</TestNode></MyTest>'
update #tblTest
set XMLColumn = cast(#xml as varchar(max))
where Id = 1
select Id, XMLColumn from #tblTest