Complex Query Incorrect Syntax Error - sql

I have tried to search for a solution to this but I have not been able to find one that fits this situation.
First I must say that my SQL is a lot rusty. The following query is the most complex one I have ever done to date.
Here is the query:
Declare #root varchar(Max)
set #root = ''
Select
ib.irrnum, ib.status, pu.probtype,
ib.submitby, ta.[Task Action], ib.area, co.cost,
rc.rootcause, ib.jobnum
From
tbl_irrbase ib
Left Join
tbl_cost co On ib.irrnum = co.irrnum
Left join
(Select Distinct probtype, irrnum
From tbl_probtype) pu On ib.irrnum = pu.irrnum
Left Join
(Select Distinct rootcause, irrnum
From tbl_rtcause) rc On ib.irrnum = rc.irrnum
Left Join
(Select TOP 1
(owner + Space(1) + Convert(varchar(10), senddate, 101) + Space(1) + taskitem) As 'Task Action',
irrnum
From
(select * From tbl_taskaction) ta
Order by
senddate Desc, sendtime Desc) ta On ib.irrnum = ta.irrnum
left Join
(Select [#root] = #root + rs.rootsource + Space(3), irrnum
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
Select #root As 'Root Source') sr On ib.irrnum = sr.irrnum
Where
ib.submitedate between '09/28/2016' And '10/05/2016'
My problem is with the last Left Join line. If I take the entire Select statement out and run it in SSMS it runs fine, no errors. But when I try and run it in this query I get an error, red squiggly line under 'Select #root As' telling me the following:
Incorrect Syntax near 'Select'.
Expecting ')', EXCEPT, or UNION
I do not know how to fix this. If I remove this last 'Left Join' line the query runs fine.
Any ideas?

Instead of the last LEFT JOIN, try something like this:
CROSS APPLY (
SELECT (
SELECT rs.rootsource + Space(3)
From tbl_rtsource rs
Where rs.entrydate Between '10/04/2016' And '10/06/2016'
AND rs.irrnum=ib.irrnum
FOR XML PATH('')
) AS rootsource
) sr
Then include sr.rootsource in the columns of the first SELECT.

Related

I am converting Oracle queries to Standard Bigquery, i am gettting error "IN subquery is not supported inside join predicate."

I have converted oracle query into below standard bq but in last statement(IN subquery). I am getting error:
"IN subquery is not supported inside join predicate."
Please advise how to use IN subquery in bq in the below code
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`domain-rr.DB_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`domain-rr.oracle_DB_DB.he_project_assoc`
INNER JOIN
`domain-rr.DB_RPT.PROJECT_GR_QTY`
ON
`domain-rr.oracle_DB_DB.he_project_assoc`.child_ISBN = `domain-
rr.DB_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `domain-rr.oracle_DB_DB.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`domain-rr.oracle_DB_DB.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
AND yy.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`domain-rr.DB_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`domain-rr.oracle_DB_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `domain-
rr.oracle_DB_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )
Can you try like this:
Select * from (
#Last part of the code
INNER JOIN (
SELECT
DISTINCT `pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN
PARENT_ISBN,
SUM (`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`.GR_QTY) GR_QTY
FROM
`pearson-rr.oracle_grdw_grdw.he_project_assoc`
INNER JOIN
`pearson-rr.GRDW_RPT.PROJECT_GR_QTY`
ON
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.child_ISBN = `pearson-
rr.GRDW_RPT.PROJECT_GR_QTY`.BIC_GCISBN
AND `pearson-rr.oracle_grdw_grdw.he_project_assoc`.BREAK_LABEL <>
'Associated ISBNs'
GROUP BY
`pearson-rr.oracle_grdw_grdw.he_project_assoc`.PARENT_ISBN) xx
ON
yy.PARENT_ISBN = xx.PARENT_ISBN
AND yy.CIRCULATION_INT < xx.GR_QTY
) AA
where AA.PARENT_ISBN IN
( SELECT
DISTINCT _BIC_GCISBN
FROM
`pearson-rr.GRDW_RPT.BIC_GM_AGCPOAODS00_BO_VW`
INNER JOIN
`pearson-rr.oracle_grdw_boadmin.fiscal_bo`
ON
_BIC_ZC2GRIRIN = 'G'
AND _BIC_ZCLOEKZ = ' '
AND SUBSTR (BOUND_DATE, 1, 6) = `pearson-
rr.oracle_grdw_boadmin.fiscal_bo`.PRIOR_FISC_YEAR_MONTH )

Error in writing SQL dynamic query

My code is like this
DECLARE #QueryText as NVARCHAR(MAX);
SET #QueryText= 'select '"' + m.MACHINE_STREET + '"' AS MACHINE_LOCATION,
A.Country_Code AS Country,
(SELECT mibcp.REMARKS FROM tblMachineContact mibcp
where mibcp.mc_machine_pkey=m.pkey and mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS
from tblMachine m inner join tblAddress A
on m.Address_Pkey=A.Pkey
where m.Site= ''TSN'''
EXEC sp_Machine_Location,NULL,NULL,NULL,#QueryText
When running this dynamic query i am getting error at sub query.
(SELECT mibcp.REMARKS
FROM tblMachineContact mibcp
WHERE mibcp.mc_machine_pkey=m.pkey
AND mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS.
How to avoid this ?
That's probably cause your below quoted subquery part will return more than 1 record and you actually meant to fetch 1 record per row.
(SELECT mibcp.REMARKS FROM tblMachineContact mibcp
where mibcp.mc_machine_pkey=m.pkey and mibcp.CONTACT_CATEGORY_PKEY=''IR'') AS REMARKS
You can probably make your query like
select m.MACHINE_STREET AS MACHINE_LOCATION,
A.Country_Code AS Country,
mibcp.REMARKS
FROM tblMachineContact mibcp
join tblMachine m on mibcp.mc_machine_pkey = m.pkey
inner join tblAddress A on m.Address_Pkey = A.Pkey
where m.Site = 'TSN'
and mibcp.CONTACT_CATEGORY_PKEY = 'IR'

SQL join on subquery with condition issue

I'm struggling when running a query on SQL. I need to strip the last 3 chars from a field that I have already created in my subquery and then join based upon that new field. The validation fails on line 5 "invalid column name 'PCD'."
SELECT
*, LEFT(SUBQUERY.PC,Len(SUBQUERY.PC) -3) AS PCD
FROM
(SELECT
PI.ClientPostcode, PI.casekey,
REPLACE( PI.ClientPostcode ,' ', '') As PC
FROM PI
WHERE LEN(PI.ClientPostcode) >= 5) AS SUBQUERY
INNER JOIN
[Postcodes] On outcode = PCD
Any help would be appreciated
You cant use the alias on the same level you defined.
SELECT *,
LEFT(SUBQUERY.pc, Len(SUBQUERY.pc) - 3) AS PCD
FROM (SELECT pi.clientpostcode,
pi.casekey,
Replace(pi.clientpostcode, ' ', '') AS PC
FROM pi
WHERE Len(pi.clientpostcode) >= 5) AS SUBQUERY
INNER JOIN [postcodes]
ON outcode = LEFT(SUBQUERY.pc, Len(SUBQUERY.pc) - 3)
^^^^ dont use the alias
Or you use it in a subquery like this
SELECT *
FROM (
SELECT *,
LEFT(SUBQUERY.pc, Len(SUBQUERY.pc) - 3) AS PCD
FROM (SELECT pi.clientpostcode,
pi.casekey,
Replace(pi.clientpostcode, ' ', '') AS PC
FROM pi
WHERE Len(pi.clientpostcode) >= 5) AS SUBQUERY
) other_subq
INNER JOIN [postcodes]
ON outcode = other_subq.PCD

Update table with date conversion failing on Multi-Part Identifier

Thanks to the guys with suggestions on date conversion yesterday, I now have a working SELECT script.
Unfortunately, when I try to turn it into an UPDATE script, I get the dreaded
Msg 4104, Level 16, State 1, Line 25
The multi-part identifier "mbrProject.ID" could not be bound.
The entire script should insert the date from mbrProject into ProjectDates, for each matching ID (mbrProject.[ID] = ProjectDates.[Project_ID]), whilst resolving mixed US & UK format dates in mbrProject, due to users having incorrect country settings when updating the tables (not changeable from my end).
Update ProjectDates
SET ProjectDates.[Start_Date] =
(
select right([Start_Date],4) +
case
when len([Start_Date])=10 then
substring([Start_Date],4,2) + left([Start_Date],2)
else right('0' + left([Start_Date],firstIndex-1),2) +
right('0' + substring([Start_Date],firstIndex+1,secondIndex - firstIndex-1),2)
end
from
(
select mp.[Start_Date], charindex('/',mp.[Start_Date],1) firstIndex,
charindex('/',mp.[Start_Date],charindex('/',mp.[Start_Date],1)+1) secondIndex
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
where mbrProject.[ID] = ProjectDates.Project_ID
)
If I run ONLY the SELECT statement, it works fine, returning the correct values.
i.e Everything from
select right([Start_Date],4) +
case
down to
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
However, as soon as I try to wrap it up in the UPDATE statement, I get the error.
I know that this is down to syntax, but wherever I try to move stuff, I can't quite figure it out.
Any ideas please?
Thanks
Craig
Try this:
UPDATE PR
SET PR.[Start_Date] = A.[Corrected_Start_Date]
FROM ProjectDates PR
JOIN
(
SELECT
[Id],
RIGHT([Start_Date],4) +
CASE
WHEN len([Start_Date])=10
THEN substring([Start_Date],4,2) + LEFT([Start_Date],2)
ELSE RIGHT('0' + LEFT([Start_Date],firstIndex-1),2) +
RIGHT('0' + substring([Start_Date],firstIndex+1,secondIndex - firstIndex-1),2)
END [Corrected_Start_Date]
FROM
(
SELECT
[Id],
[Start_Date],
charindex('/',[Start_Date],1) firstIndex,
charindex('/',[Start_Date],charindex('/',[Start_Date],1)+1) secondIndex
FROM mbrProject
) S
) A
ON A.[ID] = PR.[Project_ID]
(
select mp.[Start_Date], charindex('/',mp.[Start_Date],1) firstIndex,
charindex('/',mp.[Start_Date],charindex('/',mp.[Start_Date],1)+1) secondIndex
from mbrProject mp
join ProjectDates pd
on mp.ID = pd.Project_ID
)A
At the end of the last line here, the names mp, pd, mbrProject and (the inner ProjectDates) no longer exist as table names or aliases. The only name applicable to this row set from here on is A, the alias you've provided.
So you need to include mp.ID in your select list, and then use A.ID in your outer comparison.
Also, not knowing what you're trying to do, I'd just want to make sure you're aware that ProductDates (the table being updated) and pd are referring to two separate instances of that table, an inner one and an outer one. I'm hoping that the final WHERE should be:
where A.[ID] = ProjectDates.Project_ID
The problem is that doing
Update ProjectDates
SET ProjectDates.[Start_Date] = (select ...)
you are trying to set one field of one row to the results of the sub-select statement, which, I presume, is returning multiple values.

another union all selecting all the rows that have not already been selected

Right now i have 2 select statements that are joined by a union what i was hopping to do was maybe name the first query like query1 and the second one query2 and then in my third query do a where bookno not in query1 or query2.
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq, 'yes'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 3)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and (t0.both = t1.both)
union all
SELECT distinct t0.BOOKNO, t0.PaxName, t0.Locator, t0.FDATE7,
t0.BOARD, t0.ALIGHT, t0.AIRLINE, t0.FNUMBR, t0.DEP,
t0.ARR, t0.TOUR, t0.ROUTE,
t1.tour, t1.route, t1.sfrom , t1.sto,t1.seq,t0.seq,'YES'
FROM
( SELECT TOP (100) PERCENT test.dbo.BNAMES.BOOKNO, RTRIM(test.dbo.BNAMES.SRNAME) + '/' + RTRIM(test.dbo.BNAMES.FIRST) + RTRIM(test.dbo.BNAMES.TITLE)
AS PaxName, test.dbo.PNRS.PNR AS Locator, test.dbo.PNRSECTORS.FDATE7, test.dbo.PNRSECTORS.BOARD, test.dbo.PNRSECTORS.ALIGHT,
test.dbo.PNRSECTORS.AIRLINE, test.dbo.PNRSECTORS.FNUMBR, test.dbo.PNRSECTORS.DEP, test.dbo.PNRSECTORS.ARR, test.dbo.BOOKINGS.TOUR,
test.dbo.BOOKINGS.ROUTE, test.dbo.BSTAGES.SEQ,(test.dbo.PNRSECTORS.BOARD + test.dbo.PNRSECTORS.ALIGHT) as both
FROM test.dbo.BOOKINGS LEFT OUTER JOIN
test.dbo.BNAMES ON test.dbo.BOOKINGS.BOOKNO = test.dbo.BNAMES.BOOKNO LEFT OUTER JOIN
test.dbo.BSTAGES ON test.dbo.BNAMES.BOOKNO = test.dbo.BSTAGES.BOOKNO LEFT OUTER JOIN
test.dbo.PNRSECTORS ON test.dbo.BSTAGES.SCODE = test.dbo.PNRSECTORS.SKEY LEFT OUTER JOIN
test.dbo.PNRS ON test.dbo.PNRSECTORS.PNRKEY = test.dbo.PNRS.PNRKEY
WHERE (test.dbo.BSTAGES.STYPE = 1)
ORDER BY test.dbo.BOOKINGS.BOOKNO, test.dbo.BNAMES.SEQ, locator
) t0
INNER JOIN ( SELECT TOUR, ROUTE, OFFSET, SEQ, SCODE, SFROM, STO, (SFROM + STO) AS BOTH
FROM test.dbo.TSTAGES
) t1 ON t1.tour = t0.tour and t1.route = t0.route and t1.seq = t0.seq and (t0.both = t1.both)
order by bookno
END
How about using WITH? You can declare you queries, join them with UNION and them search for the ones not there.
Take a look here: Multiple Select Statements using SQL Server 2005 "WITH" Statement . It should help you get started.
By using WITH statement, you will isolate logic of your queries, making your overall query more understandable.
just wrap your logic around what you wrote:
select bookno
where key not in (
your big select statement...
)