Sql recursive error invalid column name CTE - visual-studio-2010

I have done following CTE it works fine,but I need to get sum of the last node so the problem is when I add T1.Debit Column to be calculated its give me an invalid column name 'Debit' !!! on line ***
ALTER Function [dbo].[SubTopics_GetSum]
-- Add the parameters for the stored procedure here
(
#TopicID int
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
WITH cte
AS (
SELECT
T1.TopicID,
T1.Code,
T1.Description,
T1.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) AS TopicDescription,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T1
LEFT OUTER JOIN Accounting.DocumentDetail
ON T1.TopicID = Accounting.DocumentDetail.TopicFK
where NOT EXISTS(
SELECT
T2.TopicID,
T2.Code,
T2.Description,
T2.ParentID,
isnull((Accounting.DocumentDetail.Debit),0) AS Debit,
isnull((Accounting.DocumentDetail.Credit),0) AS Credit
FROM Accounting.Topics AS T2
LEFT OUTER JOIN Accounting.DocumentDetail
ON T2.TopicID = Accounting.DocumentDetail.TopicFK
WHERE (ParentID = T1.TopicID)
)
UNION ALL
SELECT
c.TopicID,
c.Code,
c.Description,
c.ParentID,
T1.ParentID AS NewParentID,
CAST(T1.Code AS nvarchar(MAX)) + c.TopicCode AS TopicCode,
CAST(T1.Description AS nvarchar(MAX)) + ' - ' + c.TopicDescription AS TopicDescription,
*** isnull((T1.Debit),0)+isnull(c.Debit,0) AS Debit,--IN THIS LINE error 'Invalid Column Name 'Debit''
isnull(c.Credit,0) AS Credit
FROM cte AS c
INNER JOIN Accounting.Topics AS T1
ON T1.TopicID = c.NewParentID
)
SELECT isnull(sum(Debit),0)AS Debit,
isnull(sum(Credit),0)AS Credit
FROM cte AS c
WHERE (NewParentID = #TopicID)
)
let me know whats wrong with my code confused !!!
actually it doesn't return me a last node sum of debit,credit ... !!!
check following pic

I think below code will help,
ALTER FUNCTION [dbo].[Subtopics_getsum]
-- Add the parameters for the stored procedure here
(#TopicID INT)
returns TABLE
AS
RETURN (
-- Add the SELECT statement with parameter references here
WITH cte
AS (SELECT T1.topicid,
T1.code,
T1.description,
T1.parentid,
T1.parentid AS
NewParentID
,
Cast(T1.code AS NVARCHAR(max))
AS TopicCode,
Cast(T1.description AS NVARCHAR(max)) AS
TopicDescription,
Isnull(( accounting.documentdetail.debit ), 0) AS Debit,
Isnull(( accounting.documentdetail.credit ), 0) AS Credit
FROM accounting.topics AS T1
LEFT OUTER JOIN accounting.documentdetail
ON T1.topicid =
accounting.documentdetail.topicfk
WHERE NOT EXISTS(SELECT T2.topicid,
T2.code,
T2.description,
T2.parentid,
Isnull(( accounting.documentdetail.debit ), 0)
AS
Debit,
Isnull(( accounting.documentdetail.credit ), 0) AS
Credit
FROM accounting.topics AS T2
LEFT OUTER JOIN accounting.documentdetail
ON T2.topicid =
accounting.documentdetail.topicfk
WHERE ( parentid = T1.topicid )))
SELECT Isnull(Sum(debit), 0) AS Debit,
Isnull(Sum(credit), 0)AS Credit
FROM cte AS c
WHERE ( newparentid = #TopicID )
)

I think you Accounting.Topics hasn't column Debit.
UPDTAE
isnull((T1.Debit),0)+isnull(c.Debit,0) AS Debit,--IN THIS LINE error 'Invalid Column Name 'Debit''
isnull(c.Credit,0) AS Credit
FROM cte AS c
INNER JOIN Accounting.Topics AS T1
ON T1.TopicID = c.NewParentID
In the code above your T1.Debit refers to Accounting.Topics.

Related

Unpivot Multiple columns in Oracle is not working

I have a table like below
Process_1
Tab1_Count
Tab1_Process_Count
Tab1_Status
Process_2
Tab2_Count
Tab2_Process_Count
Tab2_Status
Tab1_Process
123
123
Equal
Tab2_Process
123
126
Not Equal
I am trying to Unpivot the above like the below
TABLEPROCESS
Tab_Count
Process_Count
Status
Tab1_Process
123
123
Equal
Tab2_Process
123
123
Not Equal
With the below query
SELECT *
FROM
(
SELECT 'Tab1' AS tab1_Process,
count(tb1.ID) AS tab1_count,
count(tbp1.ID) AS tab1_Process_count,
CASE WHEN count(tb1.ID)=count(tbp1.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab1_Status,
'Tab2' AS tab2_Process,
count(tb2.ID) AS tab2_count,
count(tbp2.ID) AS tab2_Process_count,
CASE WHEN count(tb2.ID)=count(tbp2.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab2_Status
FROM table1 tb1
LEFT JOIN table1_process tbp1 ON tbp1.ID = tb1.ID
LEFT JOIN table2 tb2 ON tb2.ID = tb1.ID
LEFT JOIN table1_process tbp2 ON tbp2.ID = tb2.ID
)
UNPIVOT
(
(TABLEPROCESS,STATUS)
FOR COUNT IN
(
(Tab1_Count,Tab2_Count) AS 'Tab_Count',
(Tab1_Process_Count,Tab2_Process_Count) AS 'Process_Count',
(Tab1_Status,Tab2_Status) AS 'STATUS'
)
)
but it is giving me error -- ORA-00907: missing right parenthesis
As per comment by Alex Poole tried CROSS APPLY method
SELECT *
FROM
(
SELECT 'Tab1' AS tab1_Process,
count(tb1.ID) AS tab1_count,
count(tbp1.ID) AS tab1_Process_count,
CASE WHEN count(tb1.ID)=count(tbp1.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab1_Status,
'Tab2' AS tab2_Process,
count(tb2.ID) AS tab2_count,
count(tbp2.ID) AS tab2_Process_count,
CASE WHEN count(tb2.ID)=count(tbp2.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab2_Status
FROM table1 tb1
LEFT JOIN table1_process tbp1 ON tbp1.ID = tb1.ID
LEFT JOIN table2 tb2 ON tb2.ID = tb1.ID
LEFT JOIN table1_process tbp2 ON tbp2.ID = tb2.ID
)
CROSS APPLY
VALUES (
(tab1_Process,Tab1_Count,Tab1_Process_Count,Tab1_Status),
(tab2_Process,Tab2_Count,Tab2_Process_Count,Tab2_Status),
) (Process,Tab_Count,Process_Count,Status);
It is working in SQL Server but it is giving ORA-00903: invalid table name in oracle
I am new to oracle, Please help
Achieved the expected result using the below UNPIVOT Query
SELECT TABLEPROCESS,TAB_COUNT,PROCESS_COUNT,STATUS
FROM
(
SELECT 'Tab1' AS tab1_Process,
count(tb1.ID) AS tab1_count,
count(tbp1.ID) AS tab1_Process_count,
CASE WHEN count(tb1.ID)=count(tbp1.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab1_Status,
'Tab2' AS tab2_Process,
count(tb2.ID) AS tab2_count,
count(tbp2.ID) AS tab2_Process_count,
CASE WHEN count(tb2.ID)=count(tbp2.ID) THEN 'Equal' ELSE 'Not Equal' END AS Tab2_Status
FROM table1 tb1
LEFT JOIN table1_process tbp1 ON tbp1.ID = tb1.ID
LEFT JOIN table2 tb2 ON tb2.ID = tb1.ID
LEFT JOIN table1_process tbp2 ON tbp2.ID = tb2.ID
)
UNPIVOT
(
(TABLEPROCESS,TAB_COUNT,PROCESS_COUNT,STATUS)
FOR (t,c,p,s)
IN
(
(tab1_Process,Tab1_Count,Tab1_Process_Count,Tab1_Status),
(tab2_Process,Tab2_Count,Tab2_Process_Count,Tab2_Status)
)
);

OR in Select Oracle

select * from table1 t1 where t1.column1 = 'someValue' and ((t1.column2 =1) OR (sysdate < select t1.DateColumn2 + t2.DateColumn2/1440
from
table2 t2 where t1.column3 = t2.column3));
if t1.column2 =1 evaluates to false, I want to check another condition if time t1.DateColumn2 + t2.DateColumn2 is < sysdate . Oracle is throwing syntax error near or condition. Cant sysdate be used directly like that? Not sure where I am going wrong. Thanks
If I am guessing your intention correctly, you want an exists clause
select *
from table1 t1
where t1.column1 = 'someValue'
and ( (t1.column2 =1)
OR exists( select 1
from table2 t2
where t2.column3 = t1.column3
and sysdate < t1.DateColumn2 + t2.DateColumn2/1440 ));
Or just join the two tables in the outer query assuming there is at most 1 row in t2 per t1 row (if there is exactly 1 row you should do an inner join rather than a left outer join)
select t1.*
from table1 t1
left outer join table2 t2
on( t1.column3 = t2.column3 )
where t1.column2 = 1
or sysdate < t1.DateColumn2 + t2.DateColumn2/1440;

How to use 'EXIST' in a simple oracle query

I have a table called ‘MainTable’ with following data
Another table called ‘ChildTable’ with following data (foreighn key Number)
Now I want to fetch those records from ‘ChildTable’ if there exists at least one ‘S’ status.
But if any other record for this number id ‘R’ then I don’t want to fetch it
Something like this-
I tried following
Select m.Number, c.Status from MainTable m, ChildTable c
where EXISTS (SELECT NULL
FROM ChildTable c2
WHERE c2.status =’S’ and c2.status <> ‘R’
AND c2.number = m.number)
But here I am getting record having ‘R’ status also, what I am doing wrong?
You can try something like this
select num, status
from
(select id, num, status,
sum(decode(status, 'R', 1, 0)) over (partition by num) Rs,
sum(decode(status, 'S', 1, 0)) over (partition by num) Ss
from child_table) t
where t.Rs = 0 and t.Ss >= 1
-- and status = 'S'
Here is a sqlfiddle demo
The child records with 'R' might be associated with a maintable record that also has another child record with status 'S' -- that is what your query is asking for.
Select
m.Number,
c.Status
from MainTable m
join ChildTable c on c.number = m.number
where EXISTS (
SELECT NULL
FROM ChildTable c2
WHERE c2.status =’S’
AND c2.number = m.number) and
NOT EXISTS (
SELECT NULL
FROM ChildTable c2
WHERE c2.status =’R’
AND c2.number = m.number)
WITH ChildrenWithS AS (
SELECT Number
FROM ChildTable
WHERE Status = 'S'
)
,ChildrenWithR AS (
SELECT Number
FROM ChildTable
WHERE Status = 'R'
)
SELECT MaintTable.Number
,ChildTable.Status
FROM MainTable
INNER JOIN ChildTable
ON MainTable.Number = ChildTable.Number
WHERE MainTable.Number IN (SELECT Number FROM ChildrenWithS)
AND MainTable.Number NOT IN (SELECT Number FROM ChildrenWithR)

CROSS APPLY too slow for running total - TSQL

Please see my code below as it is running too slowly with the CROSS APPLY.
How can I remove the CROSS APPLY and add something else that will run faster?
Please note I am using SQL Server 2008 R2.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345)
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,rt.runningTotal AS CumulativeNetWin
FROM MyCTE AS A
CROSS APPLY (SELECT SUM(NetWin) AS runningTotal
FROM MyCTE WHERE TheDay <= A.TheDay) AS rt
ORDER BY A.TheDay
CREATE TABLE #temp (NetWin money, TheDay datetime)
insert into #temp
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
FROM
dimPlayer AS P
JOIN
dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN
dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE
P.CustomerID = 12345;
SELECT
A.TheDay AS [Date]
,ISNULL(A.NetWin, 0) AS NetWin
,SUM(B.NetWin) AS CumulativeNetWin
FROM #temp AS A
JOIN #temp AS B
ON A.TheDay >= B.TheDay
GROUP BY A.TheDay, ISNULL(A.NetWin, 0);
Here https://stackoverflow.com/a/13744550/613130 it's suggested to use recursive CTE.
;WITH MyCTE AS
(
SELECT
R.NetWinCURRENCYValue AS NetWin
,dD.[Date] AS TheDay
,ROW_NUMBER() OVER (ORDER BY dD.[Date]) AS RN
FROM dimPlayer AS P
JOIN dbo.factRevenue AS R ON P.playerKey = R.playerKey
JOIN dbo.vw_Date AS dD ON Dd.dateKey = R.dateKey
WHERE P.CustomerID = 12345
)
, MyCTERec AS
(
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTE AS C
WHERE C.RN = 1
UNION ALL
SELECT C.TheDay AS [Date]
,ISNULL(C.NetWin, 0) AS NetWin
,P.CumulativeNetWin + ISNULL(C.NetWin, 0) AS CumulativeNetWin
,C.RN
FROM MyCTERec P
INNER JOIN MyCTE AS C ON C.RN = P.RN + 1
)
SELECT *
FROM MyCTERec
ORDER BY RN
OPTION (MAXRECURSION 0)
Note that this query will work if you have 1 record == 1 day! If you have multiple records in a day, the results will be different from the other query.
As I said here, if you want really fast calculation, put it into temporary table with sequential primary key and then calculate rolling total:
create table #Temp (
ID bigint identity(1, 1) primary key,
[Date] date,
NetWin decimal(29, 10)
)
insert into #Temp ([Date], NetWin)
select
dD.[Date],
sum(R.NetWinCURRENCYValue) as NetWin,
from dbo.dimPlayer as P
inner join dbo.factRevenue as R on P.playerKey = R.playerKey
inner join dbo.vw_Date as dD on Dd.dateKey = R.dateKey
where P.CustomerID = 12345
group by dD.[Date]
order by dD.[Date]
;with cte as (
select T.ID, T.[Date], T.NetWin, T.NetWin as CumulativeNetWin
from #Temp as T
where T.ID = 1
union all
select T.ID, T.[Date], T.NetWin, T.NetWin + C.CumulativeNetWin as CumulativeNetWin
from cte as C
inner join #Temp as T on T.ID = C.ID + 1
)
select C.[Date], C.NetWin, C.CumulativeNetWin
from cte as C
order by C.[Date]
I assume that you could have duplicates dates in the input, but don't want duplicates in the output, so I grouped data before puting it into the table.

Linq to entities query adding inner join instead of left join

I'd like to know why INNER JOINs are generated instead of LEFT and why the whole view is selected before join instead of just adding LEFT JOIN view.
I'm trying to post a table of information which is spread out over several tables. Basically I want to search by the date and return all the information for events happening today, yesterday, this month - whatever the user selects. The query is quite long. I added DefaultIfEmpty to all the tables except the main one in an attempt to get LEFT JOINs but it just made a mess.
using (TransitEntities t = new TransitEntities())
{
var charters = from c in t.tblCharters
join v in t.tblChartVehicles.DefaultIfEmpty()
on c.Veh
equals v.ChartVehID
join n in t.tblNACharters.DefaultIfEmpty()
on c.Dpt.Substring(c.Dpt.Length - 1)
equals SqlFunctions.StringConvert((double)n.NAID)
join r in t.tblChartReqs.DefaultIfEmpty()
on c.ChartReqID
equals r.ChartReqID
join f in t.tblCharterCustomers.DefaultIfEmpty()
on c.Dpt
equals (f.DptID == "NONAFF" ? SqlFunctions.StringConvert((double)f.CustID) : f.DptID)
join d in t.tblChartReqDocs.DefaultIfEmpty()
on c.Attach
equals SqlFunctions.StringConvert((double)d.DocID)
join s in t.tblChartSupAttaches.DefaultIfEmpty()
on c.SupAttach
equals SqlFunctions.StringConvert((double)s.DocID)
join p in (from e in t.v_EmpData select new {e.UIN, e.First, e.Last}).DefaultIfEmpty()
on c.TakenUIN
equals p.UIN
where c.BeginTime > EntityFunctions.AddYears(DateTime.Now,-1)
select new
{
ChartID = c.ChartID,
Status = c.Status,
...
Website = r.Website,
};
//select today's events
gvCharters.DataSource = charters.Where(row => (row.BeginTime.Value >= midnight && row.BeginTime.Value < midnight1));
This results in very convoluted SQL:
SELECT
[Extent1].[ChartID] AS [ChartID],
[Extent1].[Status] AS [Status],
...
[Join5].[Website] AS [Website],
FROM [dbo].[tblCharters] AS [Extent1]
INNER JOIN (SELECT [Extent2].[ChartVehID] AS [ChartVehID], [Extent2].[Descr] AS [Descr]
FROM ( SELECT 1 AS X ) AS [SingleRowTable1]
LEFT OUTER JOIN [dbo].[tblChartVehicles] AS [Extent2] ON 1 = 1 ) AS [Join1] ON ([Extent1].[Veh] = [Join1].[ChartVehID]) OR (([Extent1].[Veh] IS NULL) AND ([Join1].[ChartVehID] IS NULL))
INNER JOIN (SELECT [Extent3].[NAID] AS [NAID], [Extent3].[Descr] AS [Descr]
FROM ( SELECT 1 AS X ) AS [SingleRowTable2]
LEFT OUTER JOIN [dbo].[tblNACharter] AS [Extent3] ON 1 = 1 ) AS [Join3] ON ((SUBSTRING([Extent1].[Dpt], ((LEN([Extent1].[Dpt])) - 1) + 1, (LEN([Extent1].[Dpt])) - ((LEN([Extent1].[Dpt])) - 1))) = (STR( CAST( [Join3].[NAID] AS float)))) OR ((SUBSTRING([Extent1].[Dpt], ((LEN([Extent1].[Dpt])) - 1) + 1, (LEN([Extent1].[Dpt])) - ((LEN([Extent1].[Dpt])) - 1)) IS NULL) AND (STR( CAST( [Join3].[NAID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent4].[ChartReqID] AS [ChartReqID], [Extent4].[Event] AS [Event], [Extent4].[ContactName] AS [ContactName], [Extent4].[ContactPhone] AS [ContactPhone], [Extent4].[Website] AS [Website]
FROM ( SELECT 1 AS X ) AS [SingleRowTable3]
LEFT OUTER JOIN [dbo].[tblChartReq] AS [Extent4] ON 1 = 1 ) AS [Join5] ON ([Extent1].[ChartReqID] = [Join5].[ChartReqID]) OR (([Extent1].[ChartReqID] IS NULL) AND ([Join5].[ChartReqID] IS NULL))
INNER JOIN (SELECT [Extent5].[CustID] AS [CustID], [Extent5].[Dpt] AS [Dpt], [Extent5].[DptID] AS [DptID]
FROM ( SELECT 1 AS X ) AS [SingleRowTable4]
LEFT OUTER JOIN [dbo].[tblCharterCustomers] AS [Extent5] ON 1 = 1 ) AS [Join7] ON ([Extent1].[Dpt] = (CASE WHEN (N'NONAFF' = [Join7].[DptID]) THEN STR( CAST( [Join7].[CustID] AS float)) ELSE [Join7].[DptID] END)) OR (([Extent1].[Dpt] IS NULL) AND (CASE WHEN (N'NONAFF' = [Join7].[DptID]) THEN STR( CAST( [Join7].[CustID] AS float)) ELSE [Join7].[DptID] END IS NULL))
INNER JOIN (SELECT [Extent6].[DocID] AS [DocID], [Extent6].[FileName] AS [FileName]
FROM ( SELECT 1 AS X ) AS [SingleRowTable5]
LEFT OUTER JOIN [dbo].[tblChartReqDocs] AS [Extent6] ON 1 = 1 ) AS [Join9] ON ([Extent1].[Attach] = (STR( CAST( [Join9].[DocID] AS float)))) OR (([Extent1].[Attach] IS NULL) AND (STR( CAST( [Join9].[DocID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent7].[DocID] AS [DocID], [Extent7].[FileName] AS [FileName]
FROM ( SELECT 1 AS X ) AS [SingleRowTable6]
LEFT OUTER JOIN [dbo].[tblChartSupAttach] AS [Extent7] ON 1 = 1 ) AS [Join11] ON ([Extent1].[SupAttach] = (STR( CAST( [Join11].[DocID] AS float)))) OR (([Extent1].[SupAttach] IS NULL) AND (STR( CAST( [Join11].[DocID] AS float)) IS NULL))
INNER JOIN (SELECT [Extent8].[First] AS [First], [Extent8].[Last] AS [Last], [Extent8].[UIN] AS [UIN]
FROM ( SELECT 1 AS X ) AS [SingleRowTable7]
LEFT OUTER JOIN (SELECT
[v_EmpData].[First] AS [First],
[v_EmpData].[Last] AS [Last],
[v_EmpData].[Legal] AS [Legal],
[v_EmpData].[Name] AS [Name],
[v_EmpData].[Email] AS [Email],
[v_EmpData].[UIN] AS [UIN],
[v_EmpData].[UserNM] AS [UserNM],
[v_EmpData].[Worker] AS [Worker],
[v_EmpData].[SUPERVISORNUM] AS [SUPERVISORNUM],
[v_EmpData].[Supervisor] AS [Supervisor],
[v_EmpData].[EmpArea] AS [EmpArea],
[v_EmpData].[Title] AS [Title],
[v_EmpData].[FullName] AS [FullName],
[v_EmpData].[HireDate] AS [HireDate],
[v_EmpData].[WORKERTYPENM] AS [WORKERTYPENM],
[v_EmpData].[Birth] AS [Birth],
[v_EmpData].[HOMESTREET] AS [HOMESTREET],
[v_EmpData].[HOMECITY] AS [HOMECITY],
[v_EmpData].[HOMEZIP] AS [HOMEZIP],
[v_EmpData].[HOMESTATE] AS [HOMESTATE],
[v_EmpData].[PicID] AS [PicID],
[v_EmpData].[WorkPhone] AS [WorkPhone],
[v_EmpData].[HomePhone] AS [HomePhone],
[v_EmpData].[WorkCellPhone] AS [WorkCellPhone]
FROM [dbo].[v_EmpData] AS [v_EmpData]) AS [Extent8] ON 1 = 1 ) AS [Join13] ON ([Extent1].[TakenUIN] = [Join13].[UIN]) OR (([Extent1].[TakenUIN] IS NULL) AND ([Join13].[UIN] IS NULL))
WHERE ([Extent1].[BeginTime] > (DATEADD (year, -1, SysDateTime())))
AND ('C' <> [Extent1].[Status])
AND ([Extent1].[BeginTime] >= '11/28/2012 12:00:00 AM')
AND ([Extent1].[BeginTime] < '11/29/2012 12:00:00 AM')
This is what my original SQL query looked like and what I was hoping it would be closer to:
SELECT
ChartID,
c.Status,
...
r.Website As Website,
FROM tblChartersNew c
LEFT JOIN (SELECT [Dpt],[DptID] FROM [DRVRDiscipline].[dbo].[tblCharterCustomers] Where Valid=1 and DptID <> 'NONAFF' UNION SELECT Dpt, CONVERT(nvarchar,CustID) AS DptID FROM [DRVRDiscipline].[dbo].[tblCharterCustomers] Where Valid=1 and DptID = 'NONAFF') f
ON RTRIM(c.Dpt) = f.DptID LEFT JOIN [tskronos].WfcSuite.dbo.VP_ALLPERSONV42 p ON p.PersonNUM = c.TakenUIN
LEFT JOIN tblChartVehicles v ON v.ChartVehID = c.Veh
LEFT JOIN tblNACharter n ON CAST(n.NAID AS varchar) = RIGHT(c.Dpt, LEN(c.Dpt)-1)
LEFT JOIN tblChartReq r
ON r.ChartReqID = c.ChartReqID
WHERE CONVERT(datetime,CONVERT(char(10),c.BeginTime,101)) = (SELECT TOP 1 CONVERT(datetime,CONVERT(char(10),BeginTime,101)) from tblChartersNew WHERE CONVERT(datetime,CONVERT(char(10),BeginTime,101)) >= CONVERT(datetime,CONVERT(char(10),GETDATE(),101)) ORDER BY BeginTime)
AND NOT c.ChartReqID IS NULL
ORDER BY BeginTime, ISNULL(f.Dpt,c.Dpt)
I also add a Select New on the view to avoid selecting all of the columns when I only need three but it didn't seem to make a difference. Instead of adding LEFT JOIN v_EmpData it adds LEFT OUTER JOIN and then selects all of the columns in the view. It seems to be ignoring the Select New.
I'd really like to transition to using Linq to Entities for the majority of my queries because intellisense makes it so much easier to make sure it's right and to have variations of queries without having to have separate functions for each but maybe I need to stick with plain old SQL. I know just enough to make a big mess. Any suggestions?
For complex queries like what you need.
I would suggest looking into FunctionImport.
MSDN Function Import
This would save you the headache of creating a LINQ that would be 1:1 to your expected generated SQL.

Resources