How to parse XML attribute using MS SQL - sql

I need to get the values of attributes present in XML document using MS SQL query
Ex : I have a XML which looks below
<trade xmlns="www.somewebsite.com" Action = "Insert" TradeNumber = "1053" Volume = "25" DateTime = "2013-12-06T10:22:47.497" PNC = "false">
<Specifier Specifierid = "112" Span = "Single" Name = "Indian"/>
</trade>
I need to fetch
The values of "TradeNumber", "Volume", "DateTime" in trade tag
"Name" from Specifier tag
in a single row under their specific columns
Like
TradeNumber Volume DateTime Name
1053 25 2013-12-06T10:22:47.497 Indian
I tried using many ways but couldn't figure it out.
Please help

declare #data xml ='
<trade xmlns="www.somewebsite.com" Action = "Insert" TradeNumber = "1053" Volume = "25" DateTime = "2013-12-06T10:22:47.497" PNC = "false">
<Specifier Specifierid = "112" Span = "Single" Name = "Indian"/>
</trade>'
;with xmlnamespaces(default 'www.somewebsite.com')
select
#data.value('trade[1]/#TradeNumber', 'int') as TradeNumber,
#data.value('trade[1]/#Volume', 'int') as Volume,
#data.value('trade[1]/#DateTime', 'datetime') as [DateTime],
#data.value('(trade/Specifier)[1]/#Name', 'nvarchar(max)') as Name
--------------------------------------------------------
TradeNumber Volume DateTime Name
1053 25 2013-12-06 10:22:47.497 Indian
Or, if there're could be more than one trades:
;with xmlnamespaces(default 'www.somewebsite.com')
select
t.c.value('#TradeNumber', 'int') as TradeNumber,
t.c.value('#Volume', 'int') as Volume,
t.c.value('#DateTime', 'datetime') as [DateTime],
t.c.value('Specifier[1]/#Name', 'nvarchar(max)') as Name
from #data.nodes('trade') as t(c)

Another variant:
declare #doc xml
select #doc= '
<trade xmlns="www.somewebsite.com" Action = "Insert" TradeNumber = "1053" Volume = "25" DateTime = "2013-12-06T10:22:47.497" PNC = "false">
<Specifier Specifierid = "112" Span = "Single" Name = "Indian"/>
</trade>
'
;WITH XMLNAMESPACES('www.somewebsite.com' AS p)
SELECT
ActionAttribute = Y.i.value('(#Action)[1]', 'varchar(40)')
, TradeNumber = Y.i.value('#TradeNumber[1]', 'varchar(40)')
, Specifierid = Y.i.value('(./p:Specifier)[1]/#Specifierid', 'nvarchar(max)')
FROM
#doc.nodes('/p:trade') AS Y(i)

Related

Microsoft SQL query to view

I have this complex query that i want to turn into a view.
This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible.
`
/*##=============================================*/
/*## QUERY BODY */
/*##=============================================*/
/* #region QueryBody */
/* Testing variables !! Need to be commented for Production !! */
-- DECLARE #UserSIDs AS NVARCHAR(10) = 'Disabled';
-- DECLARE #CollectionID AS NVARCHAR(10) = 'SMS00001';
-- DECLARE #Locale AS INT = 2;
-- DECLARE #Categories AS NVARCHAR(250) = 'Tools';
-- DECLARE #Compliant AS INT = 0;
-- DECLARE #Targeted AS INT = 1;
-- DECLARE #Superseded AS INT = 0;
-- DECLARE #ArticleID AS NVARCHAR(10) = '';
-- DECLARE #ExcludeArticleIDs AS NVARCHAR(250) = '';
/* Variable declaration */
DECLARE #LCID AS INT = dbo.fn_LShortNameToLCID(#Locale);
DECLARE #HelperFunctionExists AS INT = 0;
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* Check for helper function */
IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL
SET #HelperFunctionExists = 1;
/* Initialize HealthState descriptor table */
DECLARE #HealthState TABLE (
BitMask INT
, StateName NVARCHAR(250)
)
/* Populate HealthState table */
INSERT INTO #HealthState (BitMask, StateName)
VALUES
('0', 'Healthy')
, ('1', 'Unmanaged')
, ('2', 'Inactive')
, ('4', 'Health Evaluation Failed')
, ('8', 'Pending Restart')
, ('16', 'Update Scan Failed')
, ('32', 'Update Scan Late')
, ('64', 'No Maintenance Window')
, ('128', 'Distant Maintenance Window')
, ('256', 'Expired Maintenance Window')
/* Initialize ClientState descriptor table */
DECLARE #ClientState TABLE (
BitMask INT
, StateName NVARCHAR(100)
)
/* Populate ClientState table */
INSERT INTO #ClientState (BitMask, StateName)
VALUES
('0', 'No Reboot')
, ('1', 'Configuration Manager')
, ('2', 'File Rename')
, ('4', 'Windows Update')
, ('8', 'Add or Remove Feature')
CREATE TABLE #MaintenanceInfo (
ResourceID INT
, NextServiceWindow DATETIME
)
/* Get maintenance data */
IF #HelperFunctionExists = 1
BEGIN
WITH Maintenance_CTE AS (
SELECT
CollectionMembers.ResourceID
, NextServiceWindow.Duration
, NextServiceWindow.NextServiceWindow
, RowNumber = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow)
, ServiceWindowType
, ServiceWindow.Enabled
FROM vSMS_ServiceWindow AS ServiceWindow
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID
JOIN fn_rbac_Collection(#UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID
AND Collections.CollectionType = 2 -- Device Collections
CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow
WHERE NextServiceWindow.NextServiceWindow IS NOT NULL
AND ServiceWindowType <> 5 -- OSD Service
)
/* Populate MaintenanceInfo table and remove duplicates */
INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow)
SELECT
ResourceID
, NextServiceWindow
FROM Maintenance_CTE
WHERE RowNumber = 1
END
/* Get update data */
;
WITH UpdateInfo_CTE
AS (
SELECT
ResourceID = Systems.ResourceID
, Missing = COUNT(*)
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_UpdateComplianceStatus(#UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID
AND ComplianceStatus.Status = 2 -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed)
JOIN fn_rbac_ClientCollectionMembers(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID
JOIN fn_rbac_UpdateInfo(#LCID, #UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID
AND UpdateCIs.IsSuperseded IN (#Superseded)
AND UpdateCIs.CIType_ID IN (1, 8) -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes)
AND UpdateCIs.ArticleID NOT IN ( -- Filter on ArticleID csv list
SELECT VALUE FROM STRING_SPLIT(#ExcludeArticleIDs, ',')
)
AND UpdateCIs.Title NOT LIKE ( -- Filter Preview updates
'[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%'
)
JOIN fn_rbac_CICategoryInfo_All(#LCID, #UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID
AND CICategory.CategoryTypeName = 'UpdateClassification'
AND CICategory.CategoryInstanceName IN (#Categories) -- Filter on Selected Update Classification Categories
LEFT JOIN fn_rbac_CITargetedMachines(#UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID
AND Targeted.CI_ID = ComplianceStatus.CI_ID
WHERE CollectionMembers.CollectionID = #CollectionID
AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (#Targeted) -- Filter on 'Targeted' or 'NotTargeted'
AND IIF(UpdateCIs.ArticleID = #ArticleID, 1, 0) = IIF(#ArticleID <> '', 1, 0)
GROUP BY
Systems.ResourceID
)
/* Get device info */
SELECT
Systems.ResourceID
/* Set Health states. You can find the coresponding values in the HealthState table above */
, HealthStates = (
IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Inactive/Pass'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Unknown'
, POWER(2, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Active/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
, POWER(4, 1), 0
)
+
IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0)
+
IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0)
+
IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0)
+
IIF(ISNULL(NextServiceWindow, 0) = 0 AND #HelperFunctionExists = 1, POWER(64, 1), 0)
+
IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0)
+
IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0)
)
, Missing = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL)))
, Device = (
IIF(
SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0)
, IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0)
)
)
, OperatingSystem = (
CASE
WHEN OperatingSystem.Caption0 != '' THEN
CONCAT(
REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''), -- Remove 'Microsoft ' from OperatingSystem
REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP') -- Replace 'Service Pack ' with ' SP' in OperatingSystem
)
ELSE (
/* Workaround for systems not in GS_OPERATING_SYSTEM table */
CASE
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%' THEN 'Windows 7'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%' THEN 'Windows 8'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%' THEN 'Windows 8.1'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%' THEN 'Windows 10'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.0' THEN 'Windows Server 2008'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.1' THEN 'Windows Server 2008R2'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.2' THEN 'Windows Server 2012'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.3' THEN 'Windows Server 2012 R2'
WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%' THEN (
CASE
WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019'
ELSE 'Windows Server 2016'
END
)
ELSE Systems.Operating_System_Name_And0
END
)
END
)
, LastBootTime = (
CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120)
)
, PendingRestart = (
CASE
WHEN CombinedResources.IsClient = 0
OR CombinedResources.ClientState = 0
THEN NULL
ELSE (
STUFF(
REPLACE(
(
SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()]
FROM #ClientState
WHERE BitMask & CombinedResources.ClientState <> 0
FOR XML PATH('')
),
' #!',', '
),
1, 2, ''
)
)
END
)
, ClientState = (
CASE CombinedResources.IsClient
WHEN 1 THEN ClientSummary.ClientStateDescription
ELSE 'Unmanaged'
END
)
, ClientVersion = CombinedResources.ClientVersion
, LastUpdateScan = (
CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120)
)
, LastScanLocation = NULLIF(UpdateScan.LastScanPackageLocation, '')
, LastScanError = NULLIF(UpdateScan.LastErrorCode, 0)
, NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120))
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_CombinedDeviceResources(#UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID
LEFT JOIN fn_rbac_RA_System_ResourceNames(#UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(#UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_CH_ClientSummary(#UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_UpdateScanStatus(#UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID
LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID
LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID
WHERE CollectionMembers.CollectionID = #CollectionID
AND (
CASE -- Compliant (0 = No, 1 = Yes, 2 = Unknown)
WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes
WHEN Missing > 0 AND Missing IS NOT NULL THEN 0 -- No
ELSE 2 -- Unknown
END
) IN (#Compliant)
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* #endregion */
/*##=============================================*/
/*## END QUERY BODY */
/*##=============================================*/
`
Is there an easy way to achieve this?
I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16
As I am new to SQL language I am not sure where to start.
So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do:
Wrap your code in a stored procedure.
Use OPENQUERY() to call your procedure.
Wrap the OPENQUERY() call in a view.
Limitations with this methodology is it's rather static:
You can't pass parameters to your stored procedure
If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set
The procedure can only return one result set
The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects.
Example:
-- Step 1: Wrap the procedural code in a stored procedure
CREATE PROCEDURE dbo.RunSomeCode
AS
BEGIN
CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100));
DECLARE #SomeVariable INT = 0;
WHILE (#SomeVariable < 5)
BEGIN
SET #SomeVariable = #SomeVariable + 1;
INSERT INTO #Results (ID, SomeValue)
SELECT ID, SomeValue
FROM SomeTable
WHERE ID = #SomeVariable
END
SELECT ID, SomeValue
FROM #Results;
END
GO
-- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view.
CREATE VIEW dbo.SomeView
AS
SELECT ID, SomeValue
FROM OPENQUERY
(
'
LocalServerName,
EXEC dbo.RunSomeCode
WITH RESULT SETS
((
ID INT,
SomeValue VARCHAR(100)
))
'
);
Voila, you can now execute the procedure by SELECTing from the view:
SELECT ID, SomeValue
FROM dbo.SomeView;

Cannot cast result from Sub-Select to numeric

I am selecting a list of IDs as a sub-query in a condition but it says it cannot convert '123,456' to numeric. The problem occurs in the last line. DB is Sybase-SQL-Anywhere.
SELECT
ISNULL(SUM(a.menge), 0) AS menge,
ISNULL(SUM(a.wert), 0) AS wert
FROM admin.p_ws_ix_kontrakte_ernte_auswertung_jensek a
WHERE
(a.KtrErnteJahr = ? OR ? IS NULL)
AND (
(a.KtrDispoKennz >= ? OR ? IS NULL)
AND
(a.KtrDispoKennz <= ? OR ? IS NULL)
)
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
Remove the LIST():
# replace this:
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
# with this:
AND a.artikelstammid IN (SELECT artikelstammId FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column)
Another option would be an exists/correlated subquery:
# replace this:
AND a.artikelstammid IN ((SELECT LIST(artikelstammId) FROM admin.ws_ix_auswertung_cfg_spalten_artikel WHERE columnId = $column))
# with this:
AND exists (SELECT 1 FROM admin.ws_ix_auswertung_cfg_spalten_artikel b WHERE b.columnId = $column and b.artikelstammId = a.artikelstammid)

PL/SQL Procedure to create XML

I'm very inexperienced with PL/SQL, and am tasked with creating a procedure that use need two parameters and create XML for my current select statement. I have bits and pieces of it, but am having trouble finding how to put it all together.
So I know I will need to start with the following:
PROCEDURE markviewimport_interface c_markviewimport.invoice_id NUMBER(10) = NULL c_markviewimport.filename nvarchar(30) = NULL
And I know that I will need a cursor in order to gather the data line by line.
CURSOR c_markviewimport IS SELECT DISTINCT inv.invoice_id,
vendor.segment1 vendor_num,
vendor.vendor_name,
poh.segment1 PO_NUMBER,
inv.invoice_date,
inv.invoice_num,
terms.name TERMS_NAME,
inv.invoice_amount,
inv.amount_applicable_to_discount,
inv.amount_paid,
pmt.check_date PAYMENT_DATE,
path.filename,
path.complete_filename,
path.document_id,
stamps.text,
stamps.tool_name
FROM apps.ap_invoices_all inv,
apps.ap_invoice_distributions_all dist,
apps.po_distributions_all podi,
apps.ap_invoice_payment_history_v pmt,
apps.fnd_attached_docs_form_vl fnd,
markview.mv_page_image_paths path,
apps.po_vendors vendor,
apps.po_headers_all poh,
apps.ap_terms terms,
(SELECT mp.document_id,
moi.markup_object_id,
moi.page_markups_view_id,
moi.text,
mvt.tool_name,
mp.page_id
FROM markview.mv_markup_object moi,
markview.mv_tool mvt,
markview.mv_page_markups_view mpmv,
markview.mv_page mp
WHERE moi.tool_id = mvt.tool_id
AND mp.page_id = mpmv.page_id
AND mpmv.page_markups_view_id = moi.page_markups_view_id
AND mvt.tool_id IN (SELECT mvt.tool_id
FROM markview.mv_tool
WHERE mvt.tool_name IN (
'Green Text', 'Blue Sticky Note' )
)) stamps
WHERE inv.invoice_id = To_number(fnd.pk1_value)
AND inv.invoice_id = dist.invoice_id
AND poh.po_header_id(+) = podi.po_header_id
AND podi.po_distribution_id(+) = dist.po_distribution_id
AND fnd.file_name = To_char(path.document_id)
AND inv.invoice_id = pmt.invoice_id
AND path.document_id = stamps.document_id(+)
AND path.page_id = stamps.page_id(+)
AND fnd.category_description = 'MarkView Document'
AND fnd.entity_name = 'AP_INVOICES'
AND INV.vendor_id = poh.vendor_id(+)
AND INV.terms_id = TERMS.term_id
AND inv.vendor_id = vendor.vendor_id
AND path.platform_name = 'UNIX_FS_TO_DOC_SERVER'
AND pmt.void = 'N') r_markviewimport
And lastly this is what I'm using for XML that contains every column I need.
SELECT XMLELEMENT("Item", Xmlforest(r_markviewimport.invoice_id,
r_markviewimport.vendor_num, r_markviewimport.vendor_name,
r_markviewimport.po_number,
r_markviewimport.invoice_date, r_markviewimport.invoice_num,
r_markviewimport.terms_name, r_markviewimport.invoice_amount,
r_markviewimport.amount_applicable_to_discount,
r_markviewimport.amount_paid,
r_markviewimport.payment_date,
r_markviewimport.filename, r_markviewimport.complete_filename,
r_markviewimport.document_id, r_markviewimport.text,
r_markviewimport.tool_name
)) "Item Element"
I guess I just need help, or pointed in the right direction for creating this procedure and putting it all together.
There are several ways to generate XML from tables in Oracle.
The main benefit to using the SQL functions (like XMLELEMENT and XMLFOREST) is that you don't have to iterate over a cursor line-by-line - you can do all the work in one query. Conversely, if you want to do it row-by-row with a cursor like that, using DBMS_XMLGEN would probably make more sense. You might want to do that if you have a lot of changes to make to the data before writing it to XML.
Here's a procedure to do it with XML SQL functions.
create or replace procedure markviewimport_interface (p_invoice_id number(10), p_filename nvarchar(30))
is
v_output clob;
begin
SELECT XMLELEMENT("Items", XMLAGG(XMLELEMENT("Item", Xmlforest(r_markviewimport.invoice_id,
r_markviewimport.vendor_num, r_markviewimport.vendor_name,
r_markviewimport.po_number,
r_markviewimport.invoice_date, r_markviewimport.invoice_num,
r_markviewimport.terms_name, r_markviewimport.invoice_amount,
r_markviewimport.amount_applicable_to_discount,
r_markviewimport.amount_paid,
r_markviewimport.payment_date,
r_markviewimport.filename, r_markviewimport.complete_filename,
r_markviewimport.document_id, r_markviewimport.text,
r_markviewimport.tool_name
)))).getclobval() into v_output
FROM
(SELECT DISTINCT inv.invoice_id,
vendor.segment1 vendor_num,
vendor.vendor_name,
poh.segment1 PO_NUMBER,
inv.invoice_date,
inv.invoice_num,
terms.name TERMS_NAME,
inv.invoice_amount,
inv.amount_applicable_to_discount,
inv.amount_paid,
pmt.check_date PAYMENT_DATE,
path.filename,
path.complete_filename,
path.document_id,
stamps.text,
stamps.tool_name
FROM apps.ap_invoices_all inv,
apps.ap_invoice_distributions_all dist,
apps.po_distributions_all podi,
apps.ap_invoice_payment_history_v pmt,
apps.fnd_attached_docs_form_vl fnd,
markview.mv_page_image_paths path,
apps.po_vendors vendor,
apps.po_headers_all poh,
apps.ap_terms terms,
(SELECT mp.document_id,
moi.markup_object_id,
moi.page_markups_view_id,
moi.text,
mvt.tool_name,
mp.page_id
FROM markview.mv_markup_object moi,
markview.mv_tool mvt,
markview.mv_page_markups_view mpmv,
markview.mv_page mp
WHERE moi.tool_id = mvt.tool_id
AND mp.page_id = mpmv.page_id
AND mpmv.page_markups_view_id = moi.page_markups_view_id
AND mvt.tool_id IN (SELECT mvt.tool_id
FROM markview.mv_tool
WHERE mvt.tool_name IN (
'Green Text', 'Blue Sticky Note' )
)) stamps
WHERE inv.invoice_id = To_number(fnd.pk1_value)
AND inv.invoice_id = dist.invoice_id
AND poh.po_header_id(+) = podi.po_header_id
AND podi.po_distribution_id(+) = dist.po_distribution_id
AND fnd.file_name = To_char(path.document_id)
AND inv.invoice_id = pmt.invoice_id
AND path.document_id = stamps.document_id(+)
AND path.page_id = stamps.page_id(+)
AND fnd.category_description = 'MarkView Document'
AND fnd.entity_name = 'AP_INVOICES'
AND INV.vendor_id = poh.vendor_id(+)
AND INV.terms_id = TERMS.term_id
AND inv.vendor_id = vendor.vendor_id
AND path.platform_name = 'UNIX_FS_TO_DOC_SERVER'
AND pmt.void = 'N') r_markviewimport;
DBMS_XSLPROCESSOR.clob2file(v_output, 'MY_DIRECTORY', 'output.xml');
--return v_output;
end markviewimport_interface;
/

SQL, search for true, false or both

I am currently trying to code an SQL search that can return TRUE, FALSE, or NEITHER. While the code I currently have works, I do not like the fact that I had to copy and paste a lot of code, and was wondering if there was a way to reduce the amount of code here.
DECLARE #FYear int = 2017
DECLARE #FQuarter char(2) = 'Q2'
DECLARE #FINANCIAL_GOAL_MET bit = NULL
IF(#FINANCIAL_GOAL_MET IS NULL)
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
ELSE
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
AND FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET
You can do this in one query:
DECLARE #FYear int = 2017;
DECLARE #FQuarter char(2) = 'Q2';
DECLARE #FINANCIAL_GOAL_MET bit = NULL;
SELECT FYear, FQuarter,
(CASE WHEN FINANCIAL_GOAL_MET = 'TRUE' THEN 1 ELSE 0
END) AS Financial_Goal_Met
FROM Finances f
WHERE (FYear = #FYear) AND (FQuarter = #FQuarter) AND
(#FINANCIAL_GOAL_MET IS NULL OR FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET);
For those not familiar with the bit type in SQL Server, 'TRUE' is accepted for comparison, even though it is a string.

T-SQL looping through XML data column to derive unique set of paths

I have XML data column which contains question and answer as part of an application process.
What I am trying to achieve through T-SQL/ Dynamic SQL is to derive a unique set of path wherever there is a target tag.
So for the below xml example, I would expect something like
log/clients/client/section/questions/groupone/question/target
log/clients/client/section/questions/grouptwo/question/target
Idea is to then to use this and loop through the XML to derive the values of the desired tags. I.e
[DATA].value('(/log/clients/client/section/questions/groupone/question/target', 'NVARCHAR(MAX)')
Problem is each application has different set of questions and xml structure i.e. some might have more questions, some might have different grouping.
However all I want is if there is a tag then what is its path.
How can I best achieve this?
<log>
<clients>
<client>
<section name ="Apps”>
<questions>
<groupone>
<question>
<target>Age</target>
</question>
<question>
<target> Height</target>
</question>
<question>
<target> Weight</target>
</question>
</groupone>
<grouptwo name = "exercise">
<wording>what is your name</wording>
<question>
<id>1</id>
<target>def<target>
</question>
</grouptwo>
</questions>
</section>
</client>
</clients>
</log>
The outdated approach with FROM OPENXML might be an option here. Check this answer.
At this link you'll find a function John Cappelletti posted from time to time, which will shred any XML (credits below the function's code).
But I'm not sure, what you are really trying to achieve... Why do you need the path? If you are interested in the values of all target nodes you might do something like this (deep search with // does not need the exact XPath)
SELECT t.value(N'(text())[1]','nvarchar(max)')
FROM #xml.nodes('//target') AS A(t);
If you really need all and everything you can check this:
CREATE FUNCTION [dbo].[udf-XML-Hier](#XML xml)
Returns Table
As Return
with cte0 as (
Select Lvl = 1
,ID = Cast(1 as int)
,Pt = Cast(NULL as int)
,Element = x.value('local-name(.)','varchar(150)')
,Attribute = cast('' as varchar(150))
,Value = x.value('text()[1]','varchar(max)')
,XPath = cast(concat(x.value('local-name(.)','varchar(max)'),'[' ,cast(Row_Number() Over(Order By (Select 1)) as int),']') as varchar(max))
,Seq = cast(1000000+Row_Number() over(Order By (Select 1)) as varchar(max))
,AttData = x.query('.')
,XMLData = x.query('*')
From #XML.nodes('/*') a(x)
Union All
Select Lvl = p.Lvl + 1
,ID = Cast( (Lvl + 1) * 1024 + (Row_Number() Over(Order By (Select 1)) * 2) as int ) * 10
,Pt = p.ID
,Element = c.value('local-name(.)','varchar(150)')
,Attribute = cast('' as varchar(150))
,Value = cast( c.value('text()[1]','varchar(max)') as varchar(max) )
,XPath = cast(concat(p.XPath,'/',c.value('local-name(.)','varchar(max)'),'[',cast(Row_Number() Over(PARTITION BY c.value('local-name(.)','varchar(max)') Order By (Select 1)) as int),']') as varchar(max) )
,Seq = cast(concat(p.Seq,' ',10000000+Cast( (Lvl + 1) * 1024 + (Row_Number() Over(Order By (Select 1)) * 2) as int ) * 10) as varchar(max))
,AttData = c.query('.')
,XMLData = c.query('*')
From cte0 p
Cross Apply p.XMLData.nodes('*') b(c)
)
, cte1 as (
Select R1 = Row_Number() over (Order By Seq),A.*
From (
Select Lvl,ID,Pt,Element,Attribute,Value,XPath,Seq From cte0
Union All
Select Lvl = p.Lvl+1
,ID = p.ID + Row_Number() over (Order By (Select NULL))
,Pt = p.ID
,Element = p.Element
,Attribute = x.value('local-name(.)','varchar(150)')
,Value = x.value('.','varchar(max)')
,XPath = p.XPath + '/#' + x.value('local-name(.)','varchar(max)')
,Seq = cast(concat(p.Seq,' ',10000000+p.ID + Row_Number() over (Order By (Select NULL)) ) as varchar(max))
From cte0 p
Cross Apply AttData.nodes('/*/#*') a(x)
) A
)
Select A.R1
,R2 = IsNull((Select max(R1) From cte1 Where Seq Like A.Seq+'%'),A.R1)
,A.Lvl
,A.ID
,A.Pt
,A.Element
,A.Attribute
,A.XPath
,Title = Replicate('|---',Lvl-1)+Element+IIF(Attribute='','','#'+Attribute)
,A.Value
From cte1 A
/*
Source: http://beyondrelational.com/modules/2/blogs/28/posts/10495/xquery-lab-58-select-from-xml.aspx
Taken from John Cappelletti: https://stackoverflow.com/a/42729851/5089204
Declare #XML xml='<person><firstname preferred="Annie" nickname="BeBe">Annabelle</firstname><lastname>Smith</lastname></person>'
Select * from [dbo].[udf-XML-Hier](#XML) Order by R1
*/
GO
DECLARE #xml XML=
'<log>
<clients>
<client>
<section name ="Apps">
<questions>
<groupone>
<question>
<target>Age</target>
</question>
<question>
<target> Height</target>
</question>
<question>
<target> Weight</target>
</question>
</groupone>
<grouptwo name = "exercise">
<wording>what is your name</wording>
<question>
<id>1</id>
<target>def</target>
</question>
</grouptwo>
</questions>
</section>
</client>
</clients>
</log>';
SELECT * FROM dbo.[udf-XML-Hier](#xml);
GO