I have the following statement to get both dates into #xmlData
declare #xmlData OUTOUT
SET #xmlData = (SELECT #FileDate AS [FileDate] UNION SELECT #satDate AS [FileDate] FOR XML RAW, ELEMENTS)
Then I will insert it into the table:
DECLARE #ListOfDates TABLE (FileDate varchar(50))
INSERT #ListOfDates (FileDate)
SELECT Tbl.Col.value('FileDate[1]', 'varchar(50)')
FROM #xmlData.nodes('//row') Tbl(Col)
When executing my select logic, I'm getting an error saying:
The FOR XML and FOR JSON clauses are invalid in views, inline
functions, derived tables, and subqueries when they contain a set
operator. To work around, wrap the SELECT containing a set operator
using derived table or common table expression or view and apply FOR
XML or FOR JSON on top of it.
How to fix that?
I don't see why you're using XML at all here. But the error is telling you to push down that query into a derived table (subquery) or CTE, like this:
declare #xmlData xml
declare #filedate date = getdate()
declare #satdate date = '20140101'
SET #xmlData = (
select * from
( SELECT #FileDate AS [FileDate] UNION ALL SELECT #satDate AS [FileDate] ) d
FOR XML RAW, ELEMENTS, type
)
select #xmlData
Related
Technologies: T-SQL, XML, XQuery
I have an XML #variable in a database table which has a schema section and data section. I would only like to extra only the schema section and create a XML Schema Collection for it. It appears XQuery would be the quickest way. How do I specify the starting tag and ending tag in the following file (I only want to extract everything between <xs:schema xmlns and </xs:schema>?
CREATE FUNCTION [etl].[ufn_GetXmlSchema]
(
#DataLakeBlobId uniqueidentifier
)
RETURNS xml
AS
BEGIN
DECLARE #XmlSchema xml
,#XmlData xml
SET #XmlSchema = ( SELECT [XmlData]
FROM [landing].[v_tbForm] WITH (NOLOCK)
WHERE [DataLakeBlobId] = #DataLakeBlobId
)
--RETURN #XmlSchema.query('</xs:schema>')-- missing matching begin tag
--RETURN #XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">')-- Expected end tag 'xs:schema'
RETURN #XmlSchema.query('<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet"></xs:schema>')-- nothing in between was returned
END
GO
SELECT [etl].[ufn_GetXmlSchema]('A257667D-C3AA-471C-9F82-91FA35181833')
Any help is appreciated.
While waiting for a real scenario, here is a good jump start for you. As end result, it creates an XML Schema Collection named dbo.StateAndCities.
SQL
USE tempdb;
GO
-- DDL and sample data population, start
IF EXISTS (SELECT * FROM sys.xml_schema_collections
WHERE name = N'StateAndCities'
AND schema_id = SCHEMA_ID(N'dbo'))
DROP XML SCHEMA COLLECTION dbo.StateAndCities;
DECLARE #tbl TABLE (
ID INT IDENTITY PRIMARY KEY
, state CHAR(2)
, city VARCHAR(30)
);
INSERT INTO #tbl (state, city)
VALUES
('FL', 'Miami')
, ('CA', 'Los Angeles')
, ('TX', 'Austin');
-- DDL and sample data population, end
DECLARE #xml XML
, #XSD XML;
-- Generate XML plus embedded XSD schema
SET #xml = (SELECT NULL,
(
SELECT *
FROM #tbl AS [row]
FOR XML AUTO, ELEMENTS, TYPE, XMLSCHEMA('MyURI'))
FOR XML PATH(''), TYPE, ROOT('root')
);
-- just to see, XML plus embedded XSD schema
SELECT #xml;
-- retrive just XSD
;WITH xmlnamespaces ('http://www.w3.org/2001/XMLSchema' AS xsd)
SELECT #xsd = (SELECT #xml.query('/root/xsd:schema'));
-- just to see, XSD schema
SELECT #xsd AS xsd;
-- create schema collection
CREATE XML SCHEMA COLLECTION dbo.StateAndCities AS #xsd;
My XML is stored as varbinary in a field.
SELECT cast (inboxXml as xml) FROM globalDB.Inbox WHERE inboxCId = '207435-N'
I would like to update one attribute (below). However the error is "Cannot call methods on varbinary(max)." I tried different ways to cast it, but I cannot find it.
thank you,
;WITH XMLNAMESPACES(DEFAULT 'http://www.w3.org/2001/XMLSchema')
UPDATE globalDB.Inbox
SET inboxXml.modify('replace value of (//ReceiveDeliveryHeader/DocumentID/ID/#accountingEntity[.="ABC"])[1] with "ZZZ"')
WHERE inboxCId = '207435-N'
The first question is: Why are you storing your XML within a VARBINARY column?
This is slow, clumsy and erronous...
The second thing is: .modify() will work against a real native XML only. Neither inboxXml.modify() nor CAST(inboxXml AS XML).modify() will work...
This is one more reason to change your column's type to XML...
Try this:
DECLARE #tbl TABLE(ID INT IDENTITY,YourXml VARBINARY(MAX));
DECLARE #SomeXML XML='<root><someNode someAttr="test">content</someNode></root>';
INSERT INTO #tbl VALUES(CAST(#SomeXML AS VARBINARY(MAX)));
--this works
SELECT ID
,YourXml
,CAST(YourXml AS XML)
FROM #tbl
WHERE ID=1;
--but this is not allowed
UPDATE #tbl SET CAST(YourXml AS XML).modify('replace value of (/root/someNode/#someAttr)[1] with "blah"')
WHERE ID=1
--What you can do:
DECLARE #intermediateXML XML= (SELECT CAST(YourXml AS XML) FROM #tbl WHERE ID=1);
SET #intermediateXML.modify('replace value of (/root/someNode/#someAttr)[1] with "blah"');
UPDATE #tbl SET YourXml=CAST(#intermediateXML AS VARBINARY(MAX)) WHERE ID=1;
--voila!
SELECT ID
,YourXml
,CAST(YourXml AS XML)
FROM #tbl
WHERE ID=1;
I am trying to convert data table to xml. It works fine. I want to store this converted xml in another table, So I tried using insert into select statement but it throws an error
The FOR XML clause is not allowed in a INSERT statement.
My query:
insert into table1 (column1)
select * from table2
for xml raw('product'),root('productDetails');
Updated :
This is tougher than i thought . what we have to do is
Save Xml in variable
then save Variable data to Table.(I think this can be simplified )
Code :
CREATE TABLE #MyXMLTable
(
xCol XML
) ;
DECLARE #testXML XML
SET #testXML = (
select * from "Product"
FOR XML RAW ('Product'), ROOT ('Products'));
select #testXML ;
INSERT INTO #MyXMLTable ( xCol )
SELECT #testXML;
SELECT * from #MyXMLTable
using-the-for-xml-clause-to-return-query-results-as-xml
insert-transact-sql
I would like to use something like an .Include function in SQL Server 2008, but I could not find the correct syntax for it. I have a sql query like below:
--#values has to be varchar list and start & end with comma
declare #values varchar(max) = ',7,34,37,74,85,'
select (case when #values like '%,' + m.Id + ',%' then m.Name else null end)
from #myTable m
So the logic is, if ID of a record matches with one of the numbers in #values list, I would like to see its name in the output list. This query is working fine, but I would like to find a more professional way to handle it, maybe like:
case when #values.Include(m.Id) then m.Name else null end
Any advice would be appreciated. Thanks.
The fastest method to split a delimited string is using xquery in my experience.
Ex:
DECLARE #values VARCHAR(50), #XML XML
SET #values = ',7,34,37,74,85,'
SET #XML = cast(('<X>'+replace(#values,',' ,'</X><X>')+'</X>') as xml)
SELECT N.value('.', 'VARCHAR(255)') as value FROM #XML.nodes('X') as T(N)
declare #table table (id varchar(5))
insert into #table(id)
values ('7')
select *
from #table y
where exists (SELECT 1 FROM #XML.nodes('X') as T(N) where N.value('.', 'VARCHAR(255)') = y.id)
If you are calling this code from an application, you might want to consider using Table-Valued Parameters and a stored procedure to do this.
First, you would need to create a table type to use with the procedure:
create type dbo.Ids_udt as table (Id int not null);
go
Then, create the procedure:
create procedure dbo.get_names_from_list (
#Ids as dbo.Ids_udt readonly
) as
begin;
set nocount, xact_abort on;
select t.Name
from t
inner join #Ids i
on t.Id = i.Id
end;
go
Then, assemble and pass the list of Ids to the stored procedure using a DataTable added as a SqlParameter using SqlDbType.Structured.
Table Valued Parameter Reference:
SQL Server 2008 Table-Valued Parameters and C# Custom Iterators: A Match Made In Heaven! - Leonard Lobel
Table Value Parameter Use With C# - Jignesh Trivedi
Using Table-Valued Parameters in SQL Server and .NET - Erland Sommarskog
Maximizing Performance with Table-Valued Parameters - Dan Guzman
Maximizing throughput with tvp - sqlcat
How to use TVPs with Entity Framework 4.1 and CodeFirst
Assuming that the data/list is not required to be structered as a comma separated list you could either use IN, EXISTS or SOME / ANY
If it is unavoidable you could use JiggsJedi way but since you asked for a fast way you should try to store the data in a way that in can be processed faster and does not require additional work to be queried.
IF OBJECT_ID('tempdb..#Temp') IS NOT NULL
Drop table #Temp
Create table #Temp (ID INt ,Name varchar(5))
INSERT into #Temp
SELECT 7,'AA' Union all
SELECT 34,'BA' Union all
SELECT 37,'CA' Union all
SELECT 74,'DA' Union all
SELECT 85,'TA'
DECLARE #values varchar(max) = ',,,,,,7,,34,,,74,85,,,,' --If extra commas are added in starting or end or in between of string it could handle
SET #values=','+#values+','
SELECT #values= LEFT(STUFF(#values,1,1,''),LEN(#values)-2)
DECLARE #SelectValuesIn TABLE(Value INT)
INSERT INTO #SelectValuesIn
SELECT Split.a.value('.', 'VARCHAR(100)') AS Data
FROM
(
SELECT
CAST ('<M>' + REPLACE(#values, ',', '</M><M>') + '</M>' AS XML) AS Data
) AS A CROSS APPLY Data.nodes ('/M') AS Split(a);
SELECT * FROM #Temp WHERE ID IN(SELECT Value from #SelectValuesIn)
I am using a table with an XML data field to store the audit trails of all other tables in the database.
That means the same XML field has various XML information. For example my table has two records with XML data like this:
1st record:
<client>
<name>xyz</name>
<ssn>432-54-4231</ssn>
</client>
2nd record:
<emp>
<name>abc</name>
<sal>5000</sal>
</emp>
These are the two sample formats and just two records. The table actually has many more XML formats in the same field and many records in each format.
Now my problem is that upon query I need these XML formats to be converted into tabular result sets.
What are the options for me? It would be a regular task to query this table and generate reports from it. I want to create a stored procedure to which I can pass that I need to query "<emp>" or "<client>", then my stored procedure should return tabular data.
does this help?
INSERT INTO #t (data) SELECT '
<client>
<name>xyz</name>
<ssn>432-54-4231</ssn>
</client>'
INSERT INTO #t (data) SELECT '
<emp>
<name>abc</name>
<sal>5000</sal>
</emp>'
DECLARE #el VARCHAR(20)
SELECT #el = 'client'
SELECT
x.value('local-name(.)', 'VARCHAR(20)') AS ColumnName,
x.value('.','VARCHAR(20)') AS ColumnValue
FROM #t
CROSS APPLY data.nodes('/*[local-name(.)=sql:variable("#el")]') a (x)
/*
ColumnName ColumnValue
-------------------- --------------------
client xyz432-54-4231
*/
SELECT #el = 'emp'
SELECT
x.value('local-name(.)', 'VARCHAR(20)') AS ColumnName,
x.value('.','VARCHAR(20)') AS ColumnValue
FROM #t
CROSS APPLY data.nodes('/*[local-name(.)=sql:variable("#el")]') a (x)
/*
ColumnName ColumnValue
-------------------- --------------------
emp abc5000
*/
Neither xyz432-54-4231 nor abc5000 is valid XML.
You can try to select only one particular format with a like statement, f.e.:
select *
from YourTable
where YourColumn like '[a-z][a-z][a-z][0-9][0-9][0-9][0-9]'
This would match 3 letters followed by 4 numbers.
A better option is probably to add an extra column to the table, where you save the type of the logging. Then you can use that column to select all "emp" or "client" rows.
An option would be to create a series of views that present the aduit table, per type in the relations that you're execpting
for example
select
c.value('name','nvarchar(50)') as name,
c.value('ssn', 'nvarchar(20)') as ssn
from yourtable
cross apply yourxmlcolumn.nodes('/client') as t(c)
you could then follow the same pattern for the emp
you could also create a view (or computed column) to identify each xml type like this:
select yourxmlcolumn.value('local-name(/*[1])', 'varchar(100)') as objectType
from yourtable
Use open xml method
DECLARE #idoc int
EXEC sp_xml_preparedocument #idoc OUTPUT, #xmldoc
SELECT * into #test
FROM OPENXML (#idoc, 'xmlfilepath',2)
WITH (Name varchar(50),ssn varchar(20)
)
EXEC sp_xml_removedocument #idoc
after you get the data in the #test
and you can manipulate this.
you may be put the diff data in diff xml file.