I have this query here:
SELECT
T.AKSIONERET,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
I need to retrieve, instead of T.AKSIONERET the FullAksionerCitizenship which I get from the for xml path.
I know I have to do some other SELECT but I kept getting errors, syntax errors.
Could someone help?
Thanks in advance
I'm quite sure, that there could be a better design and I'm not able to run this against test data off course, but this could work:
SELECT
T.AKSIONERET,
T2.FullAksionerCitizenship,
sd.Identification_No, sd.Date_Of_Incorp,
sd.Ownership_Desc, sd.Ownership_Code,
sd.Subject_Name_Code, sd.Subject_Name,
sd.Subject_Type_Code,
LEFT(sd.Object_Desc, 3999) AS Object_Desc,
sd.Subject_Status_Name, sd.Subject_Name,
nr2.NACE_Code, nr2.NACE_PARENT, nr2.Description,
sd.Subject_Type_Name, sd.Subject_Status_Name,
sd.Subject_Type_Name, f.Place_Of_Registration, sd.Object_Desc
FROM
NRC_Subject_DEF AS sd
LEFT JOIN
NRC_Nace_REV2 AS nr2 ON nr2.Subject_DEF_Code = sd.Subject_DEF_Code
LEFT JOIN
NRC_ForeignCompany AS f ON sd.ForeignCompany_Code = f.ForeignCompany_Code
LEFT JOIN
(SELECT
SDP.Subject_DEF_Code,
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
FOR XML PATH('')) AS AKSIONERET
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T ON T.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
--here starts the new block (difficult for me without knowing your db...)
LEFT JOIN
(SELECT
(SELECT
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc AS FullAksionerCitizenship
FROM
NRC_PeopleAddress P
INNER JOIN
NRC_SubjectDefPeople SDP1 ON SDP1.People_Code = P.People_Code
WHERE
SDP1.Subject_DEF_Code = SDP.Subject_DEF_Code
GROUP BY
SDP1.Subject_DEF_Code, P.First_Name + ' ' + P.Last_Name + '-' + P.Citizenship_Desc
) AS FullAksionerCitizenship
FROM
NRC_SubjectDefPeople SDP
WHERE
SDP.Groyp_Type IN (1,2)
GROUP BY
SDP.Subject_DEF_Code) AS T2 ON T2.Subject_DEF_Code = SD.SUBJECT_DEF_CODE
Related
For example;
I have 500 tables in database. One table is named "Table1" and another "Table234". I need to join "Table1" and "Table234" but I can't join them directly, I need to use other tables. Is it possible to make query where I enter starting table (in this case Table1) and ending table (in this case Table234) and it finds all possible paths over keys from starting to ending table.
Let's say that I have two possible paths:
Table1 -> Table 23 -> Table456 -> Table234
Table1 -> Table 34 -> Table23 -> Zable 456 -> Table234
Select * from table1
join table23 on XX = XX
join table456 on XX = XX
join table234 on XX = XX
Maybe something like BFS to find shortest path, and than save it somewhere and find BFS without that path?
Solution (#Geoff Patterson):
IF OBJECT_ID('tempdb..#paths') IS NOT NULL
DROP TABLE #paths
IF OBJECT_ID('tempdb..#shortestPaths') IS NOT NULL
DROP TABLE #shortestPaths
GO
DECLARE #targetObjectName SYSNAME = 'YourTableNameHere'
;WITH singleColumnFkColumns AS (
SELECT fk1.*
FROM sys.foreign_key_columns fk1
LEFT JOIN sys.foreign_key_columns fk2 ON fk2.constraint_object_id = fk1.constraint_object_id AND fk2.constraint_column_id = 2
WHERE fk1.constraint_column_id = 1
AND fk2.constraint_object_id IS NULL
)
, parentCTE AS (
SELECT
p.object_id AS ParentId
,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable
,pc.column_id AS ParentColumnId
,pc.name AS ParentColumn
,r.object_id AS ChildId
,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable
,rc.column_id AS ChildColumnId
,rc.name AS ChildColumn
,1 AS depth
, ',' + CONVERT(VARCHAR(MAX), p.object_id) + '_NULL_' + CONVERT(VARCHAR(MAX), pc.column_id) +
',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath
FROM sys.foreign_key_columns fk
JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id
JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id
JOIN sys.tables p ON p.object_id = fk.parent_object_id
JOIN sys.tables r ON r.object_id = fk.referenced_object_id
WHERE fk.parent_object_id = OBJECT_ID(#targetObjectName)
AND p.object_id <> r.object_id
UNION ALL
SELECT
p.object_id AS ParentId
,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable
,pc.column_id AS ParentColumnId
,pc.name AS ParentColumn
,r.object_id AS ChildId
,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable
,rc.column_id AS ChildColumnId
,rc.name AS ChildColumn
,cte.depth + 1 AS depth
,cte.TraversalPath + ',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath
FROM parentCTE cte
JOIN singleColumnFkColumns fk
ON fk.parent_object_id = cte.ChildId
JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id
JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id
JOIN sys.tables p ON p.object_id = fk.parent_object_id
JOIN sys.tables r ON r.object_id = fk.referenced_object_id
WHERE p.object_id <> r.object_id
AND cte.TraversalPath NOT LIKE ('%_' + CONVERT(VARCHAR(MAX), r.object_id) + '%')
)
SELECT *
INTO #paths
FROM parentCTE
ORDER BY depth, ParentTable, ChildTable
GO
SELECT *
INTO #shortestPaths
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY ChildTable ORDER BY depth ASC) AS rankToThisChild
FROM #paths
) x
WHERE rankToThisChild = 1
ORDER BY ChildTable
GO
WITH joinCTE AS (
SELECT p.ChildTable
, p.TraversalPath AS ParentTraversalPath
, NULL AS depth
, CONVERT(VARCHAR(MAX), 'FROM ' + p.ChildTable + ' t' + CONVERT(VARCHAR(MAX), p.depth+1)) AS JoinString
FROM #shortestPaths p
UNION ALL
SELECT cte.ChildTable
, REPLACE(p.TraversalPath, ',' + CONVERT(VARCHAR, p.ChildId) + '_' + CONVERT(VARCHAR, p.ParentColumnId)+ '_' + CONVERT(VARCHAR, p.ChildColumnId), '') AS TraversalPath
, p.depth
, cte.JoinString + '
' + CONVERT(VARCHAR(MAX), 'JOIN ' + p.ParentTable + ' t' + CONVERT(VARCHAR(MAX), p.depth) + ' ON t' + CONVERT(VARCHAR(MAX), p.depth) + '.' + p.ParentColumn + ' = t' + CONVERT(VARCHAR(MAX), p.depth+1) + '.' + p.ChildColumn) AS JoinString
FROM joinCTE cte
JOIN #paths p
ON p.TraversalPath = cte.ParentTraversalPath
)
SELECT ChildTable, 'SELECT TOP 100 *
' +JoinString
FROM joinCTE
WHERE depth = 1
ORDER BY ChildTable
GO
You can replace "YourTableNameHere" in script and it will find You all links to from any to that table.
And in my JAVA software looks like:
RS = CALIzb.main(Conn, "IF OBJECT_ID('tempdb..#paths') IS NOT NULL DROP TABLE #paths IF OBJECT_ID('tempdb..#shortestPaths') IS NOT NULL DROP TABLE #shortestPaths DECLARE #targetObjectName SYSNAME = '"+txtTablica.getText().trim()+"' ;WITH singleColumnFkColumns AS ( SELECT fk1.* FROM sys.foreign_key_columns fk1 LEFT JOIN sys.foreign_key_columns fk2 ON fk2.constraint_object_id = fk1.constraint_object_id AND fk2.constraint_column_id = 2 WHERE fk1.constraint_column_id = 1 AND fk2.constraint_object_id IS NULL ), parentCTE AS ( SELECT p.object_id AS ParentId ,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable,pc.column_id AS ParentColumnId,pc.name AS ParentColumn,r.object_id AS ChildId,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable,rc.column_id AS ChildColumnId,rc.name AS ChildColumn,1 AS depth, ',' + CONVERT(VARCHAR(MAX), p.object_id) + '_NULL_' + CONVERT(VARCHAR(MAX), pc.column_id) +',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath FROM sys.foreign_key_columns fk JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id JOIN sys.tables p ON p.object_id = fk.parent_object_id JOIN sys.tables r ON r.object_id = fk.referenced_object_id WHERE fk.parent_object_id = OBJECT_ID(#targetObjectName) AND p.object_id <> r.object_id UNION ALL SELECT p.object_id AS ParentId,OBJECT_SCHEMA_NAME(p.object_id) + '.' + p.name AS ParentTable,pc.column_id AS ParentColumnId,pc.name AS ParentColumn,r.object_id AS ChildId,OBJECT_SCHEMA_NAME(r.object_id) + '.' + r.name AS ChildTable,rc.column_id AS ChildColumnId,rc.name AS ChildColumn,cte.depth + 1 AS depth,cte.TraversalPath + ',' + CONVERT(VARCHAR(MAX), r.object_id) + '_' + CONVERT(VARCHAR(MAX), pc.column_id) + '_' + CONVERT(VARCHAR(MAX), rc.column_id) AS TraversalPath FROM parentCTE cte JOIN singleColumnFkColumns fk ON fk.parent_object_id = cte.ChildId JOIN sys.columns pc ON pc.object_id = fk.parent_object_id AND pc.column_id = fk.parent_column_id JOIN sys.columns rc ON rc.object_id = fk.referenced_object_id AND rc.column_id = fk.referenced_column_id JOIN sys.tables p ON p.object_id = fk.parent_object_id JOIN sys.tables r ON r.object_id = fk.referenced_object_id WHERE p.object_id <> r.object_id AND cte.TraversalPath NOT LIKE ('%_' + CONVERT(VARCHAR(MAX), r.object_id) + '%')) SELECT * INTO #paths FROM parentCTE ORDER BY depth, ParentTable, ChildTable SELECT * INTO #shortestPaths FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ChildTable ORDER BY depth ASC) AS rankToThisChild FROM #paths) x WHERE rankToThisChild = 1 ORDER BY ChildTable");
RS = CALIzb.main(Conn, "WITH joinCTE AS ( SELECT p.ChildTable, p.TraversalPath AS ParentTraversalPath, NULL AS depth, CONVERT(VARCHAR(MAX), 'FROM ' + p.ChildTable + ' t' + CONVERT(VARCHAR(MAX), p.depth+1)) AS JoinString FROM #shortestPaths p UNION ALL SELECT cte.ChildTable, REPLACE(p.TraversalPath, ',' + CONVERT(VARCHAR, p.ChildId) + '_' + CONVERT(VARCHAR, p.ParentColumnId)+ '_' + CONVERT(VARCHAR, p.ChildColumnId), '') AS TraversalPath, p.depth, cte.JoinString + ' ' + CONVERT(VARCHAR(MAX), 'JOIN ' + p.ParentTable + ' t' + CONVERT(VARCHAR(MAX), p.depth) + ' ON t' + CONVERT(VARCHAR(MAX), p.depth) + '.' + p.ParentColumn + ' = t' + CONVERT(VARCHAR(MAX), p.depth+1) + '.' + p.ChildColumn) AS JoinString FROM joinCTE cte JOIN #paths p ON p.TraversalPath = cte.ParentTraversalPath) SELECT ChildTable, 'SELECT TOP 100 * ' +JoinString FROM joinCTE WHERE depth = 1 ORDER BY ChildTable");
vezaKljuceva.setModel(DbUtils.resultSetToTableModel(RS));
My query is taking too much time to execute. I am using five views in left join, and I am trying to optimize the query. I am trying to remove some subquery into left join in from clause. Is it the right method to optimize because already five left joins there are? Please suggest.
How can I optimize and rewrite?
Orginal query
SELECT DISTINCT
TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS [NAME],
(SELECT MS.F_MSDSTYPE_DESC FROM T_MSDSTYPES MS WHERE MS.F_MSDSTYPE = TP.F_SUBFORMAT AND MS.F_FORMAT = TP.F_FORMAT) AS SFMT,
(SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) AS LANG,
TP.F_LANGUAGE AS LANGCODE,
TP.F_SUBFORMAT AS SFMTCODE,
TP.F_PLANT AS PLANTCODE,
TP.F_FORMAT AS FMTCODE,
CONVERT(VARCHAR,TP.F_DATE_REVISED,120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') = '') THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM T_COUNTRIES TC WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
MAN.F_PHRASE AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '') THEN TP.F_CUSTOM3 ELSE ''
END + ' ' +
CASE
WHEN NOT(SYN.F_DATA IS NULL OR SYN.F_DATA = '') THEN SYN.F_DATA ELSE ''
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM
T_PDF_MSDS TP
LEFT JOIN
T_MSDSTYPES MS ON MS.F_MSDSTYPE = TP.F_SUBFORMAT
AND MS.F_FORMAT = TP.F_FORMAT
LEFT JOIN
T_LANGUAGES TL ON TL.F_LANGUAGE = TP.F_LANGUAGE
LEFT JOIN
V_PROD_ALIAS_SYN SYN ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_SITE SIT ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_ICO IC ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_MANU MAN ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN
V_PROD_ALIAS_CASN CASN ON TP.F_PRODUCT = CASN.F_PRODUCT
WHERE
(TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '')
AND (TP.F_SUBFORMAT IN (SELECT ITEM FROM SPLIT_NEW('EGHS,VCH,VJP,EGHS,VFR,VDE,VIR,AGHS,VUS,VCA,VCH,VJP',',')))
AND (TP.F_DATE_REVISED BETWEEN '2018-07-16 15:04:31' AND '2018-07-18 21:51:45')
AND TP.F_AUTHORIZED IN (1,3)
i removed the sub query(SFMT,LANG COLUMN NAMES) by using left join like this.
SELECT DISTINCT TP.F_PRODUCT AS ID,
TP.F_PRODUCT_NAME AS [NAME],
MS.F_MSDSTYPE_DESC AS SFMT,
TL.F_LANGUAGE_NAME AS LANG,
TP.F_LANGUAGE AS LANGCODE,
TP.F_SUBFORMAT AS SFMTCODE,
TP.F_PLANT AS PLANTCODE,
TP.F_FORMAT AS FMTCODE,
CONVERT(VARCHAR,TP.F_DATE_REVISED,120) AS RDATE,
CASE
WHEN NOT(REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') IS NULL OR REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') = '') THEN REPLACE(LTRIM(RTRIM(REPLACE(TP.F_CAS_NUMBERS,'¿',' '))),' ','; ') ELSE REPLACE(LTRIM(RTRIM(REPLACE(CASN.F_DATA,'¿',' '))),' ','; ')
END AS CASNUM ,
TP.F_CUSTOM1 AS cus1,
TP.F_CUSTOM2 AS cus2,
(SELECT TC.F_COUNTRY_NAME FROM T_COUNTRIES TC WHERE TC.F_COUNTRY_CODE = TP.F_CUSTOM5) AS cus5,
MAN.F_PHRASE AS MANU,
CASE
WHEN NOT(TP.F_CUSTOM3 IS NULL OR TP.F_CUSTOM3 = '') THEN TP.F_CUSTOM3 ELSE ''
END + ' ' +
CASE
WHEN NOT(SYN.F_DATA IS NULL OR SYN.F_DATA = '') THEN SYN.F_DATA ELSE ''
END AS SYN,
IC.F_DATA AS ICO,
'SDS - ' + (SELECT TL.F_LANGUAGE_NAME FROM T_LANGUAGES TL WHERE TL.F_LANGUAGE = TP.F_LANGUAGE) + ' - PDF' AS DOC,
'' AS COVER,
CAST(TP.F_GUID AS VARCHAR(36)) + '_PDF' AS [GUID],
'PDF' AS SDS
FROM T_PDF_MSDS TP
LEFT JOIN T_MSDSTYPES MS ON
MS.F_MSDSTYPE = TP.F_SUBFORMAT
AND MS.F_FORMAT = TP.F_FORMAT
LEFT JOIN T_LANGUAGES TL ON
TL.F_LANGUAGE = TP.F_LANGUAGE
LEFT JOIN V_PROD_ALIAS_SYN SYN
ON TP.F_PRODUCT = SYN.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_SITE SIT
ON TP.F_PRODUCT = SIT.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_ICO IC
ON TP.F_PRODUCT = IC.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_MANU MAN
ON TP.F_PRODUCT = MAN.F_PRODUCT
LEFT JOIN V_PROD_ALIAS_CASN CASN
ON TP.F_PRODUCT = CASN.F_PRODUCT WHERE (TP.F_CUSTOM5 IS NULL OR TP.F_CUSTOM5 = '') AND (TP.F_SUBFORMAT IN (SELECT ITEM FROM SPLIT_NEW('EGHS,VCH,VJP,EGHS,VFR,VDE,VIR,AGHS,VUS,VCA,VCH,VJP',','))) AND (TP.F_DATE_REVISED BETWEEN '2018-07-16 15:04:31' AND '2018-07-18 21:51:45') AND TP.F_AUTHORIZED IN (1,3)
will it improve performance?
Here is the SQL Source Code for database selection that generates the following
error: "Query execution failed, Reason: SQL Error [920] [42000]:
ORA-00920: opérateur relationnel non valide.
Please Help!
WITH adr_siege as (
SELECT Nvl(adr.libadr, ' ') AS libadr, Nvl(adr.adress, ' ') AS adress,
Nvl(adr.codpos, ' ') AS codpos, Nvl(adr.locali, ' ') AS locali,
Nvl(adr.codpay, ' ') AS codpay
FROM gnx.tie
JOIN gnx.adr
ON adr.codsoc = tie.codsoc
AND adr.typtie = tie.typtie
AND adr.sigadr = tie.sigtie
AND typadr = 'COM'
WHERE tie.typtie = 'DEP'
AND tie.codsoc=1
AND tie.sigtie = '00000137'
)
SELECT Nvl(a.codpro, ' ') AS codpro, Nvl(a.nompro, ' ') AS nompro,
Nvl(ll.prix_achat, 0) AS prix_achat, Nvl(ll.qte, 0) AS qte,
Nvl(l.nom_fournisseur, ' ') AS nom_fournisseur, Nvl(m.raison, ' ') AS raison,
Nvl(concat(m.adresse1,' ' || m.adresse2), ' ') AS adresse_mag,
Nvl(m.cp, ' ') AS cp, Nvl(m.ville, ' ') AS ville,
Nvl(p.libelle, ' ') AS libelle,
Nvl(To_Char(c.date_validation, 'DD/MM/YYYY'), ' ') AS date_validation,
Nvl((
SELECT sum(fll.prix_achat * fll.qte)
FROM fourniture.frnt_livraison_ligne fll
WHERE fll.noliv
), 0) AS total_prix,
To_Char(SYSDATE, 'DD/MM/YYYY') AS date_edition,
Nvl(f.libadr, ' ') AS fou_lib_adr,
Nvl(f.tel, ' ') AS fou_tel,
Nvl(f.adress, ' ') AS fou_adr, Nvl(f.codpos, ' ') AS fou_cp,
Nvl(f.locali, ' ') AS fou_ville, Nvl(pf.libelle, ' ') AS fou_pays,
Nvl(to_char(p.date_livraison_s1, 'DD/MM/YYYY'), ' ') AS date_livraison_s1,
Nvl(to_char(p.date_livraison_s2, 'DD/MM/YYYY'), ' ') AS date_livraison_s2,
Nvl((
SELECT tbl.lib1
FROM gnx.tie
LEFT JOIN gnx.tbl
ON tbl.codtbl = 'mrg'
AND tbl.lib1 IS NOT NULL
AND tbl.codsoc=1
AND tbl.cletbl = tie.modrgl
WHERE tie.typtie = 'FOU'
AND tie.sigtie = l.code_fournisseur
AND tie.codsoc =1
), ' ') AS mode_paiement,
l.num_sous_periode,
adr_siege.*,
Nvl(m.nummag, ' ') AS nummag,
Nvl(m.tel1, ' ') AS tel1,
l.ref_gnx,
Nvl(tva.taux_tva, 0)/100 AS taux_tva,
Nvl(f.code, ' ') AS code_fournisseur,
(
CASE WHEN (m.lundi_ouverture != '0' OR m.mardi_ouverture != '0' OR m.mercredi_ouverture != '0'
OR m.jeudi_ouverture != '0' OR m.vendredi_ouverture != '0' OR m.samedi_ouverture != '0') THEN 1
ELSE 0
END
) AS AFFICH_HORRAIRE,
a.conditionnement,
a.refpro as REFPRO
FROM adr_siege, fourniture.frnt_livraison l
INNER JOIN fourniture.frnt_livraison_ligne ll ON ll.noliv = l.noliv
INNER JOIN fourniture.frnt_article a ON a.codpro = ll.codpro
INNER JOIN fourniture.frnt_commande c ON c.nocde = l.nocde
INNER JOIN polymag.magasin m ON m.nummag = c.nummag
INNER JOIN polymag.pays p ON p.code = m.codepays
LEFT JOIN fourniture.frnt_fournisseur f ON f.code =l.code_fournisseur
INNER JOIN polymag.pays pf ON pf.code = f.codpay
INNER JOIN fourniture.frnt_periode p ON p.noperiode = c.noperiode
LEFT JOIN fourniture.frnt_tva tva ON tva.code_pays_fou = f.codpay AND tva.code_pays_mag = m.codepays
WHERE l.type_livraison = 'FOU'
(we are selecting in schema named 'fournisseur')
Thank you in advance for your help.
problem is at line 25 because of WHERE fll.noliv that's without any relational operator like <,>,!,= after this statement.
TOTAL_PRIX seems to be invalid; look at its WHERE clause:
(
SELECT SUM(fll.prix_achat * fll.qte)
FROM fourniture.frnt_livraison_ligne fll
WHERE fll.noliv ), 0) AS total_prix,
k=conn:query({live=true,sql ="select DISTINCT O.OrderId, (SELECT R.ReportBody + (char(13)+char(10)) + 'Modified By: ' + UM.FirstName + ' at ' + UM.LastName + (char(13)+char(10)) +'Authored By: ' + UC.FirstName + ' at ' + UC.LastName + (char(13)+char(10)) + (char(13)+char(10)) AS [text()] FROM dbo.OrderReports R INNER JOIN dbo.Users UM ON R.ModifiedById = UM.UserId INNER JOIN dbo.Users UC ON R.CreatedById = UC.UserId WHERE R.OrderId = M[1].OrderId ORDER BY R.CreateDate DESC FOR XML PATH('')) 'OrderReport'FROM dbo.Orders O "})
I have above mentioned query and I am getting incorrect syntax error at where R.OrderId = M[1].OrderId , I am using sql with Lua.
P.S: The value in M[1].OrderId is a uniqueidentifier.
But if I have this query:
mk = conn:query({live = true, sql= "select ReportBody,DENSE_RANK() over (Order by ModifyDate DESC) from OrderReports where OrderId = '"..M[1].OrderId.."'"})
It works with M[1].OrderId though M[1].OrderId gives syntax error in the first query. How can I fix this in first query?
OK, you have not answered my last question. But assuming that the query you have written is working this is what you are after:
k=conn:query({live=true,sql ="select DISTINCT O.OrderId, (SELECT R.ReportBody + (char(13)+char(10)) + 'Modified By: ' + UM.FirstName + ' at ' + UM.LastName + (char(13)+char(10)) +'Authored By: ' + UC.FirstName + ' at ' + UC.LastName + (char(13)+char(10)) + (char(13)+char(10)) AS [text()] FROM dbo.OrderReports R INNER JOIN dbo.Users UM ON R.ModifiedById = UM.UserId INNER JOIN dbo.Users UC ON R.CreatedById = UC.UserId WHERE R.OrderId = '"..M[1].OrderId.."' ORDER BY R.CreateDate DESC FOR XML PATH('')) 'OrderReport'FROM dbo.Orders O "})
Can anyone please help me with the store procedure for the following
select statement which should take an input of completeddatekey which
is at the bottom of the select statement
CompletedDateKey is filled with a key in this code but I need a store procedure that should take an input of completeddatekey
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = '20140131'
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
Its really simple. Just create procedure like below
create procedure MyProc(
#CompletedDateKey varchar(20) )
as
Begin
SELECT FactId
,UserType
,wr.WorkRequestId
,wr.XerisUserKey
,xu.CsuserUserID UserId
,u.fname UserFName
,u.lname UserLName
,b.PatientId
,p.firstname PatFName
,p.lastname PatLName
,GroupId
,HospiceGroupKey GroupKey
,WR.ContactKey
,C.ContactId
,C.FirstName
,C.LastName
,Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )) Start_dtm
,Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay )) End_dtm
,DATEDIFF(s,
Convert(datetime,
(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay)),
Convert(datetime,
(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))) WRDuration
,(Convert(Decimal(18,3), DATEDIFF(s,Convert(datetime,(Convert(varchar, SD.Date,101) + ' ' + ST.TimeOfDay )), Convert(datetime,(Convert(varchar, CD.Date,101) + ' ' + CT.TimeOfDay ))))) * (Convert(Decimal(18,3),LineItemCount)/Convert(Decimal(18,3),PatientBucketItemCount)) Duration
,CallBackNumber
,WorkRequestType
,B.LineItemCount
,ArchiveLocation
,Processed
,ArchiveQueueType
,TQA
,Exclude
,CallId
FROM bi.dbo.FactWorkRequestTouches (NOlock) WR
INNER JOIN bi.dbo.BridgePatientWorkRequest B ON B.WorkRequestId = WR.WorkRequestId
INNER JOIN bi.dbo.dimPatient (NOlock) P ON B.PatientId = P.CphPatientID
INNER JOIN bi.dbo.DimXerisUsers (NOlock) XU ON WR.XerisUserKey = XU.XerisUserKey
INNER JOIN cdc.dbo.csuser (NOlock) U ON XU.CsuserUserID = u.user_id
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) ST ON WR.StartTimeOfDayKey = ST.TimeKey
INNER JOIN bi.dbo.DimTimeOfDay (NOlock) CT ON WR.CompletedTimeOfDayKey = CT.TimeKey
INNER JOIN bi.dbo.DimDate (NOlock) SD ON WR.StartDateKey = SD.DateKey
INNER JOIN bi.dbo.DimDate (NOlock) CD ON WR.CompletedDateKey = CD.DateKey
LEFT OUTER JOIN bi.dbo.DimContact (Nolock) C ON WR.ContactKey = C.ContactKey
left outer join ssdba.excelleRx_WebFOCUS.dbo.DimHospiceHiearchy as h with (nolock) on b.groupid = h.group_id
WHERE CompletedDateKey = #CompletedDateKey
AND ArchiveQueueType = 0
AND PatientBucketItemCount <> 0
AND Exclude = 0
AND P.ENDDate is Null
End
Execute it like
Execute MyProc '20140131'