How can I save an XML file from a SQL query? - sql

I'm using SQL Server 2019 - v15.0.4123.1.
This is the sample query (from this question):
DECLARE #tbl TABLE (ID INT IDENTITY PRIMARY KEY, city VARCHAR(30))
INSERT INTO #tbl (city)
VALUES ('Miami'), ('Orlando');
SELECT
'SIN_OPE' AS [#cod_1],
'08' AS [#cod_2],
'12' AS [#num_reg],
'yyyyyyyyyyyyyyyyyyy.xsd' AS [#xsi:noNamespaceSchemaLocation],
(SELECT *
FROM #tbl
FOR XML PATH('r'), TYPE)
FOR XML PATH('root'), TYPE, ELEMENTS XSINIL;
The result of the query is:
I just want to save/export this file as an XML file, automatically (with a stored procedure) to a folder in my PC. I've found many possible solutions but they are pretty old and doesn't work with my environment. I still can't understand if it's possible to export XML from SQL Server. I would like to avoid the manual passage "Query - Results to - Results to file"
Any advice?
Thank you

On you SQL Server Management Tool go to Query --> Result --> Result to file and then execute your query.
once you execute the query it will open a window & give you an option to save the file, there you can save it as xml.

Related

Issue with data population from XML

I am reading data from XML into a table. When I do select from the table, the table is empty.
SET #INPUTXML = CAST(#Attribute AS XML)
EXEC Sp_xml_preparedocument #TestDoc OUTPUT, #INPUTXML
SELECT Row_Number() OVER (ORDER BY Name) AS Row, *
INTO #tData
FROM OPENXML(#TestDoc, N'/DocumentElement/dtData')
WITH (
ID VARCHAR(100) './ID'
, Name VARCHAR(100) './Name'
, Value VARCHAR(max) './Value'
, Column VARCHAR(100) './Column'
)
EXEC Sp_xml_removedocument #TestDoc
Below are my questions:
select * from #tData is empty table. Why is data not getting populated?
What does Sp_xml_preparedocument do? When I print #TestDoc, it gives me a number
What is Sp_xml_removedocument ?
To answer your questions though.
#tData is empty because your SELECT statement returned no data. A SELECT...INTO statement will still create the table, even if the SELECT returns no rows. Why your SELECT is returning no data is impossible for us to say, because we have no sample data. If you remove the INTO clause you will see that no rows are returned, so you need to fix your SELECT, FROM, etc. but that brings on to my statement in a minute (about using XQUERY)
sp_xml_preparedocument (Transact-SQL) explains better than I could. Really though, you shouldn't be using it anymore, as it was used to read XML back in SQL Server 2000 (maybe 2005) and prior. Certainly SQL Server 2008 supported XQUERY, which you must be at least using if you are using SSMS 2014. To quote the opening statement of the documentation though:
Reads the XML text provided as input, parses the text by using the MSXML parser (Msxmlsql.dll), and provides the parsed document in a state ready for consumption. This parsed document is a tree representation of the various nodes in the XML document: elements, attributes, text, comments, and so on.
sp_xml_removedocument (Transact-SQL), but again, you should be using XQUERY.
Removes the internal representation of the XML document specified by the document handle and invalidates the document handle.

Result Set of procedure into XML

how can we convert the result set of a procedure into an XML without creating a temporary table since the result set may vary in their structure based on the inputs ? the scenario must work in both on premise and azure hosted SQL server databases.
CREATE PROCEDURE SPSample(#Scope VARCHAR(2))
AS
BEGIN
IF(#Scope='A')
SELECT 1 AS ID,2 AS NAME
IF(#Scope='B')
SELECT 1 AS CustomerID,'Sample#sample.com' AS Email,'121314' AS ContactNumber
END
I believe you are asking to use FOR XML or FOR XML AUTO:
https://learn.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-2017
create table mytable(col1 int, col2 nvarchar(20), col3 money)
insert into mytable(col1, col2, col3) values (1, 'string', 123.45)
select * from mytable
for xml auto
Emits:
You can do this on any query result set:
select * from sys.objects
for xml auto
This will emit that structure similarly.
i need a way that the result set from a stored procedure directly converted to XML object without creating a table structure since the result set from procedure may vary
There's no way in TSQL to do that. TSQL can only convert to XML using a SELECT, not an EXECUTE. You could do this with a loopback linked server or CLR, but those are hacks, and not available in Azure SQL DB. You'll have to find another way. EG
CREATE PROCEDURE SPSample(#Scope VARCHAR(2), #ResultsAsXml bit = 0)
. . .

Xml file node reading and inserting as seperate rows in a table

I am new bee in learning microsoft technologies.
I struck with an issue in sql server where I need your help.
Well, I have a XML file with below format,
please see it for your reference
<Permissions><Denied><User/><Roles/><Groups/></Denied><Allowed><Users/><Roles>admin,user,reader,writer,</Roles><Groups/></Allowed></Permissions>
In which I need to read Roles node values and insert those comma separated values as single row where I I will pass permissionid as a parameter in stored procedure.
here is the table columns (I need to insert single role for single row in test table based on transitionid)
create table test
(
empid int identity(1,1),
roles varchar(40),
transitionid int
)
You have two problems here: getting the data from the XML and splitting it.
If you're using SQL 2016 you're in luck - there's a new STRING_SPLIT function. You could use that like so:
declare #xml xml = '<Permissions><Denied><User/><Roles/><Groups/></Denied><Allowed><Users/><Roles>admin,user,reader,writer,</Roles><Groups/></Allowed></Permissions>';
declare #test table
(
empid int identity(1,1),
roles varchar(40),
transitionid int
)
INSERT #test (roles)
select b.value
FROM #xml.nodes('//Roles/text()')x(csv)
CROSS APPLY STRING_SPLIT(CAST(x.csv.query('.') AS VARCHAR(MAX)), ',')b
where b.value <> ''
select * from #test
Otherwise, you'll have to do something similar using a custom string splitting method, which you can find more about How do I split a string so I can access item x? or https://sqlperformance.com/2012/07/t-sql-queries/split-strings - basically, both require either writing a custom T-SQL function or CLR code that is imported into SQL Server. You could then use the same method as above (replacing STRING_SPLIT with the name of your custom string splitting function).

SQL Server Select XML Column Based on Content by User Input Values

I am developing an sql server 2012 based application.
I am a newbie to SQl server. But the requirement is to use it.
One of the table I am using contains an XML Datatype column. However the data containing in that column may vary as per the xml element. The only thing in common is the root: For instance this is a sample data:
<Tags>
<key1>Value1</key1>
<key2>Value2</key2>
<key3>Value3</key3>
<key4>Value4</key4>
<key5>Value5</key5>
<key6>Value6</key6>
</Tags>
What I want to do is to query the whole table and fetch records that will match a specific key and a specific values sent by the user.
Please assist me.
Well it sounds like you need to use some variables to build an XQuery, yes? So, assuming you build a stored procedure or something which takes a pair of string arguments for key and value you could use the following example I've knocked up in SQL Fiddle so you can try it out.
DECLARE #key nvarchar(20)
DECLARE #value nvarchar(20)
SET #key = N'key5'
SET #value = N'Value5'
SELECT
TagValue = T1.xmlcol.value('(/Tags/*[local-name()=sql:variable("#key")])[1]', 'varchar(10)')
FROM
dbo.T1
WHERE
T1.xmlcol.exist('/Tags/*[local-name()=sql:variable("#key")][text() = "Value5"]') = 1

How to get Sql Server XML variable into TEXT column

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