Currently I have an xml structure that is built like this.
<Project>
<ProjectAttribute>
<AttributeId></AttributeId>
<FieldName></FieldName>
<Title></Title>
<DisplayRow></DisplayRow>
<DisplayColumn></DisplayColumn>
<IsRequired></IsRequired>
<RequiredErrorMessage></RequiredErrorMessage>
<DevExpressControl>
<DevExpressControlId></DevExpressControlId>
<Class></Class>
<ClientNamePrefix></ClientNamePrefix>
</DevExpressControl>
<DataType>
<DataTypeId></DataTypeId>
<Name></Name>
</DataType>
</ProjectAttribute>
</Project>
I want to rename ProjectAttribute with the value of FieldName. I am unsure how to do this at the moment, seeing how when I try to put the value of that field into the XML Path, I get an error.
Here is what my sql looks like.
Set #output = (
SELECT poa.AttributeId, pa.FieldName, pa.Title, poa.DisplayRow,
poa.DisplayColumn, poa.IsRequired, pa.RequiredErrorMessage,
(SELECT de.DevExpressControlId, de.Class, de.ClientNamePrefix
FROM SCC_DevExpressControl de
WHERE de.DevExpressControlId = pa.DevExpressControlId
FOR XML Path(''), type) AS DevExpressControl,
(SELECT dt.DataTypeId, dt.Name
FROM SCC_DataType dt
WHERE dt.DataTypeId = pa.DataTypeId
FOR XML Path(''), type) AS DataType
FROM SCC_ProjectOfficeAttribute poa
LEFT JOIN SCC_ProjectAttribute pa ON poa.AttributeId = pa.AttributeId
WHERE poa.OfficeId = #OfficeId
AND poa.Status = 1
ORDER BY poa.DisplayRow, poa.DisplayColumn
FOR XML Path('ProjectAttribute'), type, Root('Project'))
select #output
#OfficeId is just an int, and #output is simply the xml. Where I am writing in the XML Path for ProjectAttribute is what I want to replace. My question is how do I get that value in there?
UPDATE: I am still somewhat at a loss. I have tried moving things like AttributeId and FieldName into the main node itself for ProjectAttribute, but this does not really fulfill my requirements.
Related
I have a column in my SQL database that is called Triggers_xml_data and its type is ntext. The column is in a xml format and I am trying to get a value from a certain part of the xml. I seen an example of this being done without a column like this:
declare #fileContent xml
set #fileContent ='<my:Header>
<my:Requestor>Mehrlein, Roswitha</my:Requestor>
<my:RequestorUserName>SJM\MehrlR01</my:RequestorUserName>
<my:RequestorEmail>RMehrlein#SJM.com</my:RequestorEmail>
<my:HRContact>Roswita Mehrlein, Beatrice Porta</my:HRContact>
<my:Entity>SJM Germany</my:Entity>
<my:Department>HR/Administration</my:Department>
<my:PositionTitle>Sales Representative</my:PositionTitle>
<my:JobDescription>x0lGQRQAAAABAAAAAAAAAAAeAQAyAAAAVgBAAAAA=</my:JobDescription>
<my:PositionDepartment>Sales</my:PositionDepartment>'
;WITH XMLNAMESPACES ('http://schemas.microsoft.com/office/infopath/2003/myXSD/2005-08-29T12-58-51' as my)
select #fileContent.value('(//my:PositionDepartment)[1]', 'varchar(255)')
But I want to select my column like this:
Declare #filevalue xml
select de.triggers_xml_data
from dbo.DEPLOYMENT_ENVIRONMENT as de
But this is not working and I tried to use this #filecontent.value('(//value)[1]','varchar(255)') and making it equal the column value, I have tried casting it but I can't find a way to do this. Is this possible?
When I do this:
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(triggers/triggerDefinition/config/item/value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
I am getting a null value returned.
Here is an example of what my xml could look like:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration xml:space="preserve">
<triggers>
<defined>true</defined>
<triggerDefinition>
<id>1</id>
<name>After successful deployment</name>
<userDescription/>
<isEnabled>true</isEnabled>
<pluginKey>com.atlassian.bamboo.triggers.atlassian-bamboo-triggers:afterSuccessfulDeployment</pluginKey>
<triggeringRepositories/>
<config>
<item>
<key>deployment.trigger.afterSuccessfulDeployment.triggeringEnvironmentId</key>
<value>19234819</value>
</item>
</config>
</triggerDefinition>
</triggers>
<bambooDelimiterParsingDisabled>true</bambooDelimiterParsingDisabled>
</configuration>
The XML, as you posted it, is not valid. Your code example does not work... It is not allowed to use a namespace prefix without a namespace declaration. Furthermore your example misses the closing Header-tag...
I corrected this...
DECLARE #yourTbl TABLE(ID INT, YourXML NTEXT);
INSERT INTO #yourTbl VALUES
(1,N'<my:Header xmlns:my="DummyUrl">
<my:Requestor>Mehrlein, Roswitha</my:Requestor>
<my:RequestorUserName>SJM\MehrlR01</my:RequestorUserName>
<my:RequestorEmail>RMehrlein#SJM.com</my:RequestorEmail>
<my:HRContact>Roswita Mehrlein, Beatrice Porta</my:HRContact>
<my:Entity>SJM Germany</my:Entity>
<my:Department>HR/Administration</my:Department>
<my:PositionTitle>Sales Representative</my:PositionTitle>
<my:JobDescription>x0lGQRQAAAABAAAAAAAAAAAeAQAyAAAAVgBAAAAA=</my:JobDescription>
<my:PositionDepartment>Sales</my:PositionDepartment>
</my:Header>');
--Lazy approach
SELECT ID
,CAST(CAST(YourXml AS NVARCHAR(MAX)) AS XML).value(N'(//*:PositionDepartment)[1]','nvarchar(max)')
FROM #yourTbl;
--explicit approach
WITH XMLNAMESPACES('DummyUrl' AS my)
SELECT ID
,CAST(CAST(YourXml AS NVARCHAR(MAX)) AS XML).value(N'(/my:Header/my:PositionDepartment)[1]','nvarchar(max)')
FROM #yourTbl
Some Background
If possible you should not store XML in other format than XML and further more one should avoid NTEXT, as it is depricated since SS2005!.
You have to cast NTEXT to NVARCHAR(MAX) first, than cast this to XML. The second will break, if the XML is not valid. That means: If the XML is really the way you posted it, this cannot work!
UPDATE: String-based approach, if XML does not work
If you cannot cast this to XML you might try this
--String based
WITH Casted AS
(
SELECT ID
,CAST(YourXML AS NVARCHAR(MAX)) AS TheXmlAsString
FROM #yourTbl
)
,WithPosition AS
(
SELECT Casted.*
,CHARINDEX(N'<my:PositionDepartment>',TheXmlAsString) + LEN(N'<my:PositionDepartment>') AS FirstLetter
FROM Casted
)
SELECT ID
,SUBSTRING(TheXmlAsString,FirstLetter,CHARINDEX('<',TheXmlAsString,FirstLetter)-FirstLetter)
FROM WithPosition
UPDATE 2
According to your edit the following returns a NULL value. This is good, because it shows, that the cast was successfull.
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(triggers/triggerDefinition/config/item/value)[1]',
'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
Try this (skip namespace with wildcard):
SELECT
CAST(
REPLACE(CAST(de.TRIGGERS_XML_DATA AS VARCHAR(MAX)), 'encoding="utf-16"', '')
AS XML).value('(*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
And this should be even better:
SELECT
CAST(CAST(de.TRIGGERS_XML_DATA AS NVARCHAR(MAX)) AS XML).value('(*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item, de.ENVIRONMENT_ID
from dbo.DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
UPDATE 3
I'd rather cut away the full declaration. Your posted example would go like this
DECLARE #DEPLOYMENT_ENVIRONMENT TABLE(ENVIRONMENT_ID INT, TRIGGERS_XML_DATA NTEXT);
INSERT INTO #DEPLOYMENT_ENVIRONMENT VALUES
(19234819,N'<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<configuration xml:space="preserve">
<triggers>
<defined>true</defined>
<triggerDefinition>
<id>1</id>
<name>After successful deployment</name>
<userDescription/>
<isEnabled>true</isEnabled>
<pluginKey>com.atlassian.bamboo.triggers.atlassian-bamboo-triggers:afterSuccessfulDeployment</pluginKey>
<triggeringRepositories/>
<config>
<item>
<key>deployment.trigger.afterSuccessfulDeployment.triggeringEnvironmentId</key>
<value>19234819</value>
</item>
</config>
</triggerDefinition>
</triggers>
<bambooDelimiterParsingDisabled>true</bambooDelimiterParsingDisabled>
</configuration>');
WITH Casted AS
(
SELECT CAST(de.TRIGGERS_XML_DATA AS NVARCHAR(MAX)) AS XmlAsSting
FROM #DEPLOYMENT_ENVIRONMENT as de
where de.ENVIRONMENT_ID = 19234819
)
SELECT CAST(SUBSTRING(XmlAsSting,CHARINDEX('?>',XmlAsSting)+2,8000) AS XML).value('(/*:configuration/*:triggers/*:triggerDefinition/*:config/*:item/*:value)[1]', 'NVARCHAR(max)') as Item
FROM Casted;
I have database with two tables: Transaction and from_person.
I need to convert it to specified format like this:
<transaction>
<transaction_number>TRNWEB0147</transaction_number
<transaction_location>felesteen</transaction_location>
<date_transaction>2016-05-25T00:00:00</date_transaction>
<from_funds_code>C</from_funds_code>
<from_person>
<gender>M</gender>
<title>Mr.</title>
<first_name>Mohamed</first_name>
<middle_name>Mohamed</middle_name>
<prefix>AHMED</prefix>
<last_name>yahia</last_name>
<birth_date>1984-11-16T00:00:00</birth_date>
<ssn>28411160225124</ssn>
</from_person>
</transaction>
I try to do this query:
select tr.transactionnumber
,tr.transaction_location
,tr.transaction_description
,tr.date_transaction
,tr.teller
,tr.authorized
,tr.transmode_
,tr.amount_local
,(select fp.from_funds_code
,fp.from_country
from from_person fp
where fp.from_funds_code = tr.t_from_my_client
for xml path(''), elements, type)
from dbo. [ transaction ] tr
for xml path(''), elements, type
but result become in this format:
<transaction_number>TRNWEB0147</transaction_number
<transaction_location>felesteen</transaction_location>
<date_transaction>2016-05-25T00:00:00</date_transaction>
<from_funds_code>C</from_funds_code>
<gender>M</gender>
<title>Mr.</title>
<first_name>Mohamed</first_name>
<middle_name>Mohamed</middle_name>
<prefix>AHMED</prefix>
<last_name>yahia</last_name>
<birth_date>1984-11-16T00:00:00</birth_date>
<ssn>28411160225124</ssn>
I tried many ways but not succeed, please help.
Please use this query.
SELECT transaction_number,transaction_location,date_transaction,from_funds_code,
(
SELECT gender,title,first_name,middle_name,prefix,last_name,birth_date,ssn
FROM from_person FP
WHERE FP.FROM_FUNDS_CODE =TR.T_FROM_MY_CLIENT
FOR XML PATH('from_person'), ELEMENTS, TYPE
)
FROM dbo.[TRANSACTION] TR
FOR XML PATH('transaction'), ELEMENTS, TYPE
I am trying to generate an XML string based on data in two SQL tables. One contains Order Header data, the other one Line Item data.
My problem is that I can't get the Line Item info to appear properly as multiple elements within a single order:
This is the SQL statement:
Select
LTRIM(RTRIM(H.CustPONbr)) As "Transactions/Transaction/CustomerOrdNumber",
(
Select LTRIM(RTRIM(InvtID)) As "data()" From X888_Amazon_Order_Line L1
Where L1.CpnyID = H.CpnyID And L1.CustPONbr = H.CustPONbr
FOR XML PATH (''), ELEMENTS
) As "Transactions/Transaction/LineItems/LineItem/InvtId"
From X888_Amazon_Order_Header H (nolock)
where h.CustPONbr = '99999014'
For XML PATH ('ProcessEngineSubmission'), Root ('XML'), ELEMENTS
This is the result that I get:
<XML>
<Transactions>
<Transaction>
<CustomerOrdNumber>99999014</CustomerOrdNumber>
<LineItems>
<LineItem>
<InvtId>TEST 1235 TEST 1234</InvtId>
</LineItem>
</LineItems>
</Transaction>
</Transactions>
</XML>
If I execute the inner select (replacing "data()" with InvtId), I get what I am trying to achieve:
<InvtId>TEST 1235</InvtId>
<InvtId>TEST 1234</InvtId>
Try it like this:
Nested selects need the ,TYPE extension to come back as XML...
You might need to specify a path in the inner PATH('') or give a name to the column with AS ...
Select LTRIM(RTRIM(H.CustPONbr)) As "Transactions/Transaction/CustomerOrdNumber"
,(
Select LTRIM(RTRIM(InvtID))
From X888_Amazon_Order_Line L1
Where L1.CpnyID = H.CpnyID And L1.CustPONbr = H.CustPONbr
FOR XML PATH (''), TYPE
) As "Transactions/Transaction/LineItems/LineItem/InvtId"
From X888_Amazon_Order_Header H (nolock)
where h.CustPONbr = '99999014'
For XML PATH ('ProcessEngineSubmission'), Root ('XML')
All
I have very little experience of xml, so please be gentle.
The situation is we use an application called dataswitch to take xml and process it into our ERP system via business objects.
The output I am trying to recreate is as follows from a sample xml document.
**<?xml version="1.0" encoding="Windows-1252" ?>
- <IssueDetails Language="05" CssStyle="" DecFormat="1" DateFormat="01" Role="01" Version="6.0.000">**
- <Item>
<Job>00000121</Job>
<NonStocked>N</NonStocked>
<Warehouse>RM</Warehouse>
<StockCode>BBMB100</StockCode>
<Line>00</Line>
<QuantityToIssue>1.000</QuantityToIssue>
</Item>
</IssueDetails>
So far I have worked on the For xml Path method to build my query and used the sp from Phil Factor to write the output
So far I have been successful creating an xml document which opens in the browser (many tries required!)
This is the output I have managed to create, please note the top lines are different
**<IssueDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">**
- <Item>
<Job>00044816</Job>
<NonStocked>N</NonStocked>
<Warehouse>C2</Warehouse>
<StockCode>FG00707</StockCode>
<Line>00</Line>
<QuantityToIssue>400.000000000</QuantityToIssue>
</Item>
- <Item>
<Job>00044816</Job>
<NonStocked>N</NonStocked>
<Warehouse>C2</Warehouse>
<StockCode>FG00707</StockCode>
<Line>00</Line>
<QuantityToIssue>10.000000000</QuantityToIssue>
</Item>
</IssueDetails>
So my question is how do I get the top line in my output to be the same as the sample output?
My procedure is listed below
Declare
#XML_1 varchar (max),
#myXML varchar(max),
#myFile varchar (30),
#Path varchar (100)
set #XML_1=''
set #myFile ='MaterialIssuesTest.xml'
set #Path='D:\Temp\'
--Query database for materials
Set #XML_1 =#XML_1 + ( SELECT WJM.[Job]
,Case when WJM.[Warehouse]='**' then 'Y' else 'N' end as NonStocked
,WJM.[Warehouse]
,rtrim(LP.StockCode) as StockCode
,WJM.[Line]
,[UnitQtyReqd]*LP.LQtyComplete as QuantityToIssue
FROM [SysproCompanyR].[dbo].[WipJobAllMat] WJM
inner join CHC_Production.LabPostsAtMileOps LP On WJM.Job=LP.Job
Where WJM.Job in ('00044816')and (WJM.OperationOffset > LP.PrevOp
and WJM.OperationOffset<LP.LOperation)
FOR XML Path ('Item'),ROOT ('IssueDetails'), ELEMENTS XSINIL
)
set #myXML = LTRIM(rtrim(#XML_1))
--Debug print xml
Print #myXML
--Output xml to document
execute dbo.spWriteStringToFile #myXML, #Path, #myFile
GO
To get you first line, which is a child element of the main body you need to do a sub query like what I have done below. To get the attributes you need to name them with the # symbol, again in my example (formatting changes to aid me setting it out!):
SET #XML_1 =#XML_1 +
(
SELECT WJM.[Job],
(
SELECT '' AS '#Language',
'' AS '#CssStyle',
'' AS '#DecFormat',
'' AS '#DateFormat',
'' AS '#Role',
'' AS '#Version'
FROM YOURTABLENAME YTN
WHERE YTN.[SOMEFIELD] = WJM.[SOMEFIELD]
FOR XML PATH(''), TYPE
) AS 'IssueDetails'
,Case when WJM.[Warehouse]='**' then 'Y' else 'N' end as NonStocked
,WJM.[Warehouse]
,rtrim(LP.StockCode) as StockCode
,WJM.[Line]
,[UnitQtyReqd]*LP.LQtyComplete as QuantityToIssue
FROM [SysproCompanyR].[dbo].[WipJobAllMat] WJM
INNER JOIN CHC_Production.LabPostsAtMileOps LP ON WJM.Job = LP.Job
WHERE WJM.Job IN ('00044816') AND (WJM.OperationOffset > LP.PrevOp
AND WJM.OperationOffset<LP.LOperation)
FOR XML Path ('Item'), ROOT ('IssueDetails'), ELEMENTS XSINIL
)
I don't know where the data is coming from, so you will have to fill in the table name and the WHERE clause to join it to the data that you already have. That is assuming the data is a child of the data that you have already provided.
Bare in mind the syntax might not be quite correct as I am doing this from memory and there are several different variations to get this result.
I'm trying to SELECT from a table containing XML column. I would like to obtain specific node and have a row created for each one.
The XML is directly obtained from Reporting Services database and contains RDL (report) structure. My goal is to display all ‹Textbox›‹Value›example‹/Value›‹/Textbox› values for each report. The location of ‹Textbox› nodes is unpredictable (it can be part of any element somewhere in XML structure).
Below is the current code, but for some reason id doesn't work:
IF object_id('tempdb..#c') IS NOT NULL
DROP TABLE #c
select top 50
path as reportpath
,name as reportname
,convert(xml, convert(varbinary(max), content)) as reportxml
into
#c
from
reportserver.dbo.catalog
where
content is not null
order by creationdate desc
-----------------------------------------
DECLARE #x XML
SELECT #x =
( SELECT
[reportpath]
,[reportname]
,[reportxml].query('
for $a in //../Textbox
return ‹Textbox
valueX="{$a/Value}"
/›
')
FROM #c AS reports
FOR XML AUTO
)
select #x
-----------------------------------------
SELECT [reportpath] = T.Item.value('../#reportpath', 'nvarchar(max)'),
[reportname] = T.Item.value('../#reportname', 'nvarchar(max)'),
value = T.Item.value('#value' , 'nvarchar(max)')
FROM #x.nodes('//reports/Textbox') AS T(Item)
Example below shows sample "Textbox" containg a "Value":
‹RowGrouping›
‹Width›2.53968cm‹/Width›
‹DynamicRows›
‹Grouping Name="matrix1_OperationalWeek2"›
‹GroupExpressions›
‹GroupExpression›=Fields!OperationalWeek.Value‹/GroupExpression›
‹/GroupExpressions›
‹/Grouping›
‹ReportItems›
‹Textbox Name="textbox35"›
‹rd:DefaultName›textbox35‹/rd:DefaultName›
‹Style›
‹BackgroundColor›White‹/BackgroundColor›
‹PaddingLeft›2pt‹/PaddingLeft›
‹PaddingRight›2pt‹/PaddingRight›
‹PaddingTop›2pt‹/PaddingTop›
‹PaddingBottom›2pt‹/PaddingBottom›
‹/Style›
‹ZIndex›8‹/ZIndex›
‹Value›=Fields!OperationalWeek.Value‹/Value›
‹/Textbox›
‹/ReportItems›
‹/DynamicRows›
‹/RowGrouping›
PS I had some trouble with stackoverflow code formatting so I replaced < and > marks with ‹ and ›. Sorry about that.
Based on Bret's Blog ([http://blogs.netconnex.com/2011/05/extracting-ssrs-report-rdl-xml-from.html][1])
and adding the namespace gets you results... I wish I could claim I understand well enough to explain but I mostly find my way by "stumbling" through it.
--================================================
;WITH XMLNAMESPACES (
DEFAULT 'http://schemas.microsoft.com/sqlserver/reporting/2008/01/reportdefinition',
'http://schemas.microsoft.com/SQLServer/reporting/reportdesigner' AS rd --ReportDefinition
)
select top 50
c.Path as reportpath
--, c.name as reportname
,t.value('#Name','VARCHAR(100)') as TextboxName
,t.value('data(Paragraphs/Paragraph/TextRuns/TextRun/Value)[1]', 'varchar(max)') as value
from
reportserver.dbo.catalog c
cross apply
(select convert(xml, convert(varbinary(max), content))) as R(reportxml)
cross apply
--Get all the Query elements (The "*:" ignores any xml namespaces)
r.reportxml.nodes('//*:Textbox') n(t)
where
content is not null
and c.Type = 2 -- Reports
order by creationdate desc
This simple XQuery:
for $a in //Textbox
return
<Textbox
valueX="{$a/Value}"
/>
when applied on the provided XML document (namespace definition added to make it well-formed):
<RowGrouping xmlns:rd="rd">
<Width>2.53968cm</Width>
<DynamicRows>
<Grouping Name="matrix1_OperationalWeek2">
<GroupExpressions>
<GroupExpression>=Fields!OperationalWeek.Value</GroupExpression>
</GroupExpressions>
</Grouping>
<ReportItems>
<Textbox Name="textbox35">
<rd:DefaultName>textbox35</rd:DefaultName>
<Style>
<BackgroundColor>White</BackgroundColor>
<PaddingLeft>2pt</PaddingLeft>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<PaddingBottom>2pt</PaddingBottom>
</Style>
<ZIndex>8</ZIndex>
<Value>=Fields!OperationalWeek.Value</Value>
</Textbox>
</ReportItems>
</DynamicRows>
</RowGrouping>
produces the wanted, correct result:
<?xml version="1.0" encoding="UTF-8"?>
<Textbox valueX="=Fields!OperationalWeek.Value"/>
Therefore, if you cannot get result, your problem is in something else, not in the XQuery code.
I can't test if this works but it should do what you want.
select top 50
path as reportpath
,name as reportname
,n.t.value('Value[1]', 'varchar(max)') as value
from
reportserver.dbo.catalog
cross apply
(select convert(xml, convert(varbinary(max), content))) as c(reportxml)
cross apply
c.reportxml.nodes('//Textbox') n(t)
where
content is not null
order by creationdate desc