oracle-databasevisual-studiocommon-table-expressiontableadaptersubquery-factoring

Using a CTE in Visual Studio 3 Queries


I'm trying to get results from a subquery created as a SQL statement in a tableadapter in Visual Studio. The project is linked to an oracle database. I was originally trying to use a "with" clause, which works fine in Oracle, but not so much as a SQL query in Visual Studio. When I used the "with" clause, the error said "unable to parse query". Without the "with" clause I got the first two queries (Query 1 and Query 2) to work fine together in the tableadapter, but when I add the Main Query, I get an error 'SELECT' not recognized. FYI: I also tried using a stored procedure that the dataset would connect to but would not work on the Visual Studio side, so for now, I'm hoping to accomplish this with a SQL statement, rather than the stored procedure. Any help is appreciated.

    --- Query 1 ---

 SELECT * from (select
  ss.startdate
 ,ss.enddate
 ,s.segid
 ,s.segno
 ,s.stats
 ,sp.spo
 ,p.pro
FROM
 Spon ss
,Segs s
,pro p
,spo sp
WHERE
 and     ss.segid    =       s.segid
 and     ss.spoid    =       sp.spoid
 and     p.proid    =       sp.proid            
 and     ss.startdate    <=      (par_date1)
 and     ss.enddate      >=      (par_date2)
) sss,

    --- Query 2 ---

 (
SELECT
  p.pickid
  ,p.segid
  ,p.spid
  ,p.pickdate
  ,p.pickqty
FROM      picks p
WHERE
        (P.Pickdate is null or P.Pickdate between  (par_date1) and  ((par_date2))  )
) ppp

    --- Query 3 (MAIN Query - Queries data pulled from Query 1 and Query 2) ---

 SELECT
  sss.shipid
 ,sss.segno
 ,To_Char(sss.StartDate, 'DD-MON-YYYY')  As StartDate
 ,To_Char(sss.EndDate, 'DD-MON-YYYY')  As EndDate
 ,sss.Spo
 ,sss.Pro
 ,To_Char(ppp.PickDate, 'DD-MON-YYYY') As PickDate
 ,To_Char(Max(ppp.PickDate), 'DD-MON-YYYY')   As LastPick
 ,Round(SUM(ppp.PickQty/(Count(distinct sss.spid)) ,2 )  As Avrg
 ,Count(sss.spid)  As TtlPicks
 ,sum(ppp.PickQty) As Ttls
    FROM sss, ppp
   WHERE
        ppp.spid(+)     =       sss.spid
   GROUP BY
 sss.shipid
,sss.segno
,sss.Spo
,sss.Pro
,To_Char(sss.StartDate, 'DD-MON-YYYY')
,To_Char(sss.EndDate, 'DD-MON-YYYY')
,To_Char(ppp.PickDate, 'DD-MON-YYYY')

Solution

  • Locate the FROM clause in the main (outer) query: FROM sss, ppp Replace it with

    FROM ( placeholder_1 ) sss, 
         ( placeholder_2 ) ppp
    

    where placeholder_1 should be replaced with the full text of Query #1 and placeholder_2 with the full text of Query #2.

    You may want to consider using ANSI standard syntax for the outer query... and in GROUP BY you will save time if you group by trunc(sss.startdate) and similar for the other dates; the effect is the same.

    Good luck!