I'm quite new to SQL, I needed to create a data source which includes data from many different tables. I wrote following script. It works for low amount of data but when data size improves,it becomes impossible to get the data via this query. How can i improve this script, what might be the possible bottlenecks and keypoints ? Thanks in advance.
SELECT
dbo.IDW_COSTDETAIL.IDW_PROJECT_FK, dbo.IDW_PROJECT_DATA.CODE + ' - ' +
dbo.IDW_PROJECT_DATA.DESCRIPTION AS PROJECT,
dbo.IDW_PROJECT_ALTERNATIVE.CODE + ' - ' + dbo.IDW_PROJECT_ALTERNATIVE.DESCRIPTION AS PRJ_ALTERNATIVE,
dbo.IDW_COSTDETAIL.BOQ_NO,
dbo.IDW_COSTDETAIL.IDW_CONTROLLING_CODE_FK AS BUDGETCODE,
dbo.IDW_CONTROLLING_CODE.DESCRIPTION AS BC_DESCR,
dbo.IDW_ACTIVITY.CODE AS ACTIVITY_ID,
dbo.IDW_ACTIVITY.DESCRIPTION AS ACTIVITY_DESCR, dbo.IDW_BOQ_DETAIL.REFERENCE,
dbo.IDW_BOQ_DETAIL.OUTLINE_SPEC1, dbo.IDW_BOQ_DETAIL.UOM AS ITEM_UOM,
dbo.IDW_COSTDETAIL.COST_CODE,
dbo.IDW_COSTDETAIL.COMMODITY_CODE,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.DESCRIPTION
ELSE IDW_COMMODITIES.DESCRIPTION
END AS SUBITEM_DESCR,
dbo.IDW_BOQ_DETAIL.AQ_QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS ITEM_AQ,
dbo.IDW_COSTDETAIL.QUANTITY_BASED_AQ / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS SUBITEM_AQ,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.UOM
ELSE IDW_COMMODITIES.UOM
END AS SUBITEM_UOM,
dbo.IDW_COSTDETAIL.COST / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS UNIT_COST,
CASE
WHEN IDW_COSTDETAIL.COMMODITY_CODE IS NULL
THEN IDW_COST_CODE.CURRENCY
ELSE IDW_COMMODITIES.ESTIMATE_CURRENCY
END AS CATALOG_CUR,
dbo.IDW_BOQ_DETAIL.IQ_QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS ITEM_IQ,
dbo.IDW_COSTDETAIL_IQ.QUANTITY / (DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) + 1) AS SUBITEM_IQ,
dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE, DATEDIFF(day, dbo.IDW_ACTIVITY.START_DATE, dbo.IDW_ACTIVITY.END_DATE) AS DURATION,
dbo.SQLCALENDAR.DateKey AS FULLDATE,
dbo.IDW_COST_CODE_HIER_V.CODE + ' - ' + dbo.IDW_COST_CODE_HIER_V.DESCRIPTION AS CODE,
dbo.IDW_COST_CODE_HIER_V.COC_LVL1 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL1 AS COC_LVL1,
dbo.IDW_COST_CODE_HIER_V.COC_LVL2 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL2 AS COC_LVL2,
dbo.IDW_COST_CODE_HIER_V.COC_LVL3 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL3 AS COC_LVL3,
dbo.IDW_COST_CODE_HIER_V.COC_LVL4 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL4 AS COC_LVL4,
dbo.IDW_COST_CODE_HIER_V.COC_LVL5 + ' - ' + dbo.IDW_COST_CODE_HIER_V.COC_DESC_LVL5 AS COC_LVL5,
dbo.IDW_COMMODITIES_HIER_V.CODE + ' - ' + dbo.IDW_COMMODITIES_HIER_V.DESCRIPTION AS COMMODITY,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL1 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL1 AS COM_LVL1, dbo.IDW_COMMODITIES_HIER_V.COM_LVL2 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL2 AS COM_LVL2,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL3 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL3 AS COM_LVL3, dbo.IDW_COMMODITIES_HIER_V.COM_LVL4 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL4 AS COM_LVL4,
dbo.IDW_COMMODITIES_HIER_V.COM_LVL5 + ' - ' + dbo.IDW_COMMODITIES_HIER_V.COM_DESC_LVL5 AS COM_LVL5
FROM
dbo.IDW_PROJECT_DATA
INNER JOIN
dbo.IDW_ACTIVITY
INNER JOIN
dbo.IDW_COSTDETAIL ON dbo.IDW_ACTIVITY.IDW_PROJECT_FK = dbo.IDW_COSTDETAIL.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_ACTIVITY.CODE = dbo.IDW_COSTDETAIL.IDW_ACTIVITY_FK
INNER JOIN
dbo.IDW_CONTROLLING_CODE ON dbo.IDW_COSTDETAIL.IDW_CONTROLLING_CODE_FK = dbo.IDW_CONTROLLING_CODE.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_FK ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_ACTIVITY.IDW_PROJECT_FK
INNER JOIN
dbo.IDW_PROJECT_ALTERNATIVE ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_ACTIVITY.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE AND dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_FK = dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK AND dbo.IDW_CONTROLLING_CODE.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_PROJECT_ALTERNATIVE.CODE
RIGHT OUTER JOIN
dbo.IDW_BOQ_DETAIL ON dbo.IDW_PROJECT_ALTERNATIVE.CODE = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_PROJECT_ALTERNATIVE.IDW_PROJECT_FK = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.ITEM_REFERENCE = dbo.IDW_BOQ_DETAIL.REFERENCE AND dbo.IDW_COSTDETAIL.BOQ_NO = dbo.IDW_BOQ_DETAIL.IDW_BOQ_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_BOQ_DETAIL.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COST_CODE ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_COST_CODE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COST_CODE.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.COST_CODE = dbo.IDW_COST_CODE.CODE
LEFT OUTER JOIN
dbo.IDW_COMMODITIES ON dbo.IDW_PROJECT_DATA.IDW_PROJECT_FK = dbo.IDW_COMMODITIES.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COMMODITIES.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.COMMODITY_CODE = dbo.IDW_COMMODITIES.CODE
LEFT OUTER JOIN
dbo.IDW_COST_CODE_HIER_V ON dbo.IDW_COSTDETAIL.COST_CODE = dbo.IDW_COST_CODE_HIER_V.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COST_CODE_HIER_V.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COMMODITIES_HIER_V ON dbo.IDW_COSTDETAIL.COMMODITY_CODE = dbo.IDW_COMMODITIES_HIER_V.CODE AND dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COMMODITIES_HIER_V.IDW_PROJECT_FK
LEFT OUTER JOIN
dbo.IDW_COSTDETAIL_IQ ON dbo.IDW_COSTDETAIL.IDW_PROJECT_FK = dbo.IDW_COSTDETAIL_IQ.IDW_PROJECT_FK AND dbo.IDW_COSTDETAIL.IDW_PROJECT_ALTERNATIVE_FK = dbo.IDW_COSTDETAIL_IQ.IDW_PROJECT_ALTERNATIVE_FK AND dbo.IDW_COSTDETAIL.ID = dbo.IDW_COSTDETAIL_IQ.IDW_COSTDETAIL_FK
CROSS JOIN
dbo.SQLCALENDAR
WHERE
(dbo.IDW_BOQ_DETAIL.ITEM_KIND = 2)
AND (dbo.SQLCALENDAR.DateKey BETWEEN CONVERT(CHAR(8), dbo.IDW_ACTIVITY.START_DATE, 112) AND CONVERT(CHAR(8), dbo.IDW_ACTIVITY.END_DATE, 112))
Run the script in SSMS, generate the execution plan, and create the indicies it suggests.
Related
I am trying to generate the combinations of each possible team fitting the rules for a league. I have two different methods that I have approached. One is do everything in one single select.
Mind you there are probably about 16 qbs 32 rbs 104 wrs 32 te's 16 dsts 16 k's and then 168 fx's. After 10 hours I generated millions of items but it still hadn't worked its way through completely.
SELECT
QB.name, RB1.name, RB2.name, WR1.name, WR2.name, WR3.name, TE.name, FX.name, K.name, DST.name,
(QB.salary + RB1.salary + RB2.salary + WR1.salary + WR2.salary + WR3.salary + TE.salary + FX.salary + K.salary + DST.salary) AS cost,
(QB.projectedFloor + RB1.projectedFloor + RB2.projectedFloor + WR1.projectedFloor + WR2.projectedFloor + WR3.projectedFloor + TE.projectedFloor + FX.projectedFloor + K.projectedFloor + DST.projectedFloor) AS lowest,
(QB.projectedCeiling + RB1.projectedCeiling + RB2.projectedCeiling + WR1.projectedCeiling + WR2.projectedCeiling + WR3.projectedCeiling + TE.projectedCeiling + FX.projectedCeiling + K.projectedCeiling + DST.projectedCeiling) AS highest,
(QB.projectedPoints + RB1.projectedPoints + RB2.projectedPoints + WR1.projectedPoints + WR2.projectedPoints + WR3.projectedPoints + TE.projectedPoints + FX.projectedPoints + K.projectedPoints + DST.projectedPoints) AS projection
FROM quarterbacks QB
INNER JOIN defense DST
ON DST.defenseId = DST.defenseId
INNER JOIN kicker K
ON K.kickerId = K.kickerId
INNER JOIN tightends TE
ON TE.playersId = TE.playersId
INNER JOIN runningbacks RB1
ON RB1.playersId = RB1.playersId
INNER JOIN runningbacks RB2
ON RB2.playersId = RB2.playersId
INNER JOIN receivers WR1
ON WR1.playersId = WR1.playersId
INNER JOIN receivers WR2
ON WR2.playersId = WR2.playersId
INNER JOIN receivers WR3
ON WR3.playersId = WR3.playersId
INNER JOIN flex FX
ON FX.playersId = FX.playersId
WHERE
RB1.runningbacksId != RB2.runningbacksId AND
WR1.receiversId != WR2.receiversId AND
WR1.receiversId != WR3.receiversId AND
WR2.receiversId != WR3.receiversId AND
FX.playersId != RB1.playersId AND
FX.playersId != RB2.playersId AND
FX.playersId != WR1.playersId AND
FX.playersId != WR2.playersId AND
FX.playersId != WR3.playersId AND
FX.playersId != TE.playersId AND
(QB.salary + RB1.salary + RB2.salary + WR1.salary + WR2.salary + WR3.salary + TE.salary + K.salary + DST.salary) < 50000 AND
(QB.salary + RB1.salary + RB2.salary + WR1.salary + WR2.salary + WR3.salary + TE.salary + K.salary + DST.salary) > 45000
AND
(QB.projectedPoints + RB1.projectedPoints + RB2.projectedPoints + WR1.projectedPoints + WR2.projectedPoints + WR3.projectedPoints + TE.projectedPoints + FX.projectedPoints + K.projectedPoints + DST.projectedPoints) > 100
ORDER BY
(QB.projectedCeiling + RB1.projectedCeiling + RB2.projectedCeiling + WR1.projectedCeiling + WR2.projectedCeiling + WR3.projectedCeiling + TE.projectedCeiling + FX.projectedCeiling + K.projectedCeiling + DST.projectedCeiling),
(QB.projectedPoints + RB1.projectedPoints + RB2.projectedPoints + WR1.projectedPoints + WR2.projectedPoints + WR3.projectedPoints + TE.projectedPoints + FX.projectedPoints + K.projectedPoints + DST.projectedPoints),
(QB.projectedFloor + RB1.projectedFloor + RB2.projectedFloor + WR1.projectedFloor + WR2.projectedFloor + WR3.projectedFloor + TE.projectedFloor + FX.projectedFloor + K.projectedFloor + DST.projectedFloor)
I also have another approach in which I may not be understanding clearly if it would be faster. It involves making smaller tables and then joining them together.
DECLARE #QBSRBS TABLE (
qb nvarchar(max),
rb1 nvarchar (max),
rb2 nvarchar (max),
cost int,
highest float,
lowest float,
points float
);
DECLARE #WRS TABLE (
wr1 nvarchar(max),
wr2 nvarchar(max),
wr3 nvarchar(max),
cost int,
highest float,
lowest float,
points float
);
DECLARE #TEsDSTK TABLE (
te nvarchar(max),
fx nvarchar(max),
dst nvarchar(max),
k nvarchar(max),
cost int,
highest float,
lowest float,
points float
);
INSERT INTO #QBSRBS
SELECT
QB.name, RB1.name, RB2.name,
(QB.salary + RB1.salary + RB2.salary ) AS cost,
(QB.projectedFloor + RB1.projectedFloor + RB2.projectedFloor) AS lowest,
(QB.projectedCeiling + RB1.projectedCeiling + RB2.projectedCeiling) AS highest,
(QB.projectedPoints + RB1.projectedPoints + RB2.projectedPoints) AS projection
FROM quarterbacks QB
INNER JOIN runningbacks RB1
ON RB1.playersId = RB1.playersId
INNER JOIN runningbacks RB2
ON RB2.playersId = RB2.playersId
WHERE
RB1.runningbacksId != RB2.runningbacksId AND
RB1.team != RB2.team
INSERT INTO #WRS
SELECT
WR1.name, WR2.name, WR3.name,
(WR1.salary + WR2.salary + WR3.salary) AS cost,
(WR1.projectedFloor + WR2.projectedFloor + WR3.projectedFloor) AS lowest,
(WR1.projectedCeiling + WR2.projectedCeiling + WR3.projectedCeiling) AS highest,
(WR1.projectedPoints + WR2.projectedPoints + WR3.projectedPoints) AS projection
FROM receivers WR1
INNER JOIN receivers WR2
ON WR2.playersId = WR2.playersId
INNER JOIN receivers WR3
ON WR3.playersId = WR3.playersId
WHERE WR1.receiversId != WR2.receiversId AND
WR1.receiversId != WR3.receiversId AND
WR2.receiversId != WR3.receiversId AND
WR1.team != WR2.team AND WR1.team != WR3.team AND
WR2.team != WR3.team
INSERT INTO #TEsDSTK
SELECT TE.name, FX.name, K.name, DST.name,
(TE.salary + FX.salary + K.salary + DST.salary) AS cost,
(TE.projectedFloor + FX.projectedFloor + K.projectedFloor + DST.projectedFloor) AS lowest,
(TE.projectedCeiling + FX.projectedCeiling + K.projectedCeiling + DST.projectedCeiling) AS highest,
(TE.projectedPoints + FX.projectedPoints + K.projectedPoints + DST.projectedPoints) AS projection
FROM kicker K
INNER JOIN tightends TE
ON TE.playersId = TE.playersId
INNER JOIN flex FX
ON FX.playersId = FX.playersId
INNER JOIN defense DST
ON DST.defenseId = DST.defenseId
WHERE TE.playersId != FX.playersId
SELECT
qb, rb1, rb2, wr1, wr2, wr3, te, fx, k, dst,
(QR.cost + WR.cost + TFDK.cost) as cost,
(QR.lowest + WR.lowest + TFDK.lowest ) as lowest,
(QR.highest + WR.highest + TFDK.highest) as highest,
(QR.points + WR.points + TFDK.points) as points
FROM #QBSRBS QR
INNER JOIN #TEsDSTK TFDK
ON TFDK.cost = TFDK.cost
INNER JOIN #WRS WR
ON WR.cost = WR.cost
WHERE
QR.rb1 != TFDK.fx AND
QR.rb2 != TFDK.fx AND
WR.wr1 != TFDK.fx AND
WR.wr2 != TFDK.fx AND
WR.wr3 != TFDK.fx AND
(QR.highest + WR.highest + TFDK.highest) > 203
How can I improve the efficiency of this?
SELECT
CONCAT(SG.firstname +' ', SG.lastName) AS 'Name',
SG.entityId 'ID',
dbo.GetTitleDescriptionByEntityID(SG.entityId) 'Title',
CASE ISNULL(EC.address2, '')
WHEN '' THEN EC.address1
ELSE EC.address1 +', ' + EC.address2
END +', ' + EC.city + ', ' + LDState.ItemName + ', ' + EC.zip 'Address',
CR.clinicalRate
FROM
StaffGeneral SG WITH (NOLOCK)
JOIN
LookupDetails LD WITH (NOLOCK) ON SG.employeeStatus = LD.lookupDetailsId AND LD.ItemAbbreviation = 'SCSSC'
JOIN
othersRating or1 WITH (nolock) ON SG.entityId = or1.entityId AND dateRated = (SELECT TOP 1 MAX(dateRated) FROM OthersRating r1 WITH (nolock) WHERE r1.entityid = SG.entityId)
JOIN
LookupDetails LDRating with (nolock) ON or1.rating = LDRating.lookupDetailsId AND LDRating.ItemAbbreviation NOT IN ('RTNP', 'RTDNU', 'RTPENDING', 'RTDELETE', 'RTTERMI')
JOIN
EntityContacts EC with (nolock) ON SG.entityId = EC.entityId AND (eC.contactId = 'General' or EC.contactId = 'General1') AND EC.deleted = 0
JOIN
LookupDetails LDState WITH (NOLOCK) ON EC.state = LDState.lookupDetailsId
JOIN
ContractorRate CR ON SG.entityId = CR.entityId AND CR.deleted = 0
WHERE
SG.isActive = 0 AND SG.deleted = 0
AND ((SG.entityId = #subContractorID) OR (#subContractorID IS null))
AND ((#subContractorName IS NULL) OR ((EC.firstName + ' ' + EC.lastName) LIKE #subContractorName + '%'))
In the above query I wanted to concat the first and last name with space and query it against the input to the stored procedure #subcontractorname.
When the subcontractorname is null that is fine but I am not able to get results when it jumps to Or clause .
Tried the SQL Server Profiler but does not show anything how the query is formed
I tried executing the SQL by putting the whole SQL in a var but I am hitting the problem of varchar(max).
Please advise
I have a query - which is combining with a Union statement the 5 columns into 2 columns.
So basically - an ID + Some Information. As the ID could be in column 2-5 - several times... I rearranged to be everything in one ID column + the text.
Now - I wanted to use a second "with" statement - to combine the IDs of several rows - with a XML path. But here I got stuck.
That is the code - which gives me the two column - with content as expected:
With
STall as (Select
'Status: ' + ST.Status + Char(10) + 'Crew Information:' + Char(10) +
'Instructor: ' + ST.IP + Char(10) + 'Student: ' + ST.SP + Char(10) + Case
When ST.ACM1 = 'NA' Then '' Else 'ACM1: ' + ST.ACM1 + Char(10) End + Case
When ST.ACM2 = 'NA' Then '' Else 'ACM2: ' + ST.ACM2 + Char(10)
End + 'Lesson: ' + ST.Lesson + Char(10) + Case
When ST.ScheduleRemarks = '' Then ''
Else ' REM:' + ST.ScheduleRemarks + Char(10)
End + 'Equipment: ' + ST.EquipmentName + ' (' + ST.Callsign + ')' +
Char(10) + 'Start: ' + Convert(VARCHAR(10),ST.ScheduleTO,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTO,108) + ' UTC' + Char(10) + 'End: ' +
Convert(VARCHAR(10),ST.ScheduleTD,104) + ' - ' +
Convert(VARCHAR(5),ST.ScheduleTD,108) + ' UTC' + Char(10) + Case
When ST.ATC = 'NA' Then '' Else ST.ATC End As SInfo,
ST.IDIP,
ST.IDSP,
ST.IDA1,
ST.IDA2
From
(Select
Case When Schedule.StatusRelease = 1 Then 'OK' Else Case
When Schedule.StatusRequest = 1 Then 'STBY' Else 'N/A' End
End As Status,
Schedule.ContactIDIP,
Schedule.ContactIDSP,
MasterLesson.Lesson,
Equipment.EquipmentName,
CallSignList.Callsign,
Schedule.Meeting,
Schedule.ScheduleRemarks,
Schedule.StatusRelease,
Schedule.StatusRequest,
Schedule.ScheduleDay,
ContactList.FullNameTLC As IP,
ContactList1.FullNameTLC As SP,
Case When Schedule.ContactIDACM1 = 0 Then 'NA'
Else ContactList2.FullNameTLC End As ACM1,
Case When Schedule.ContactIDACM2 = 0 Then 'NA'
Else ContactList3.FullNameTLC End As ACM2,
Schedule.ScheduleTO,
Schedule.ScheduleTD,
Case When Schedule.RouteID = 0 Then 'NA'
Else 'Route: ' + Airport.ICAO + ' - ' + Case
When IsNull(Airport1.ICAO, 'NA') = 'NA' Then ' '
Else Airport1.ICAO + ' - ' End + Airport2.ICAO + Char(10) + Char(13)
End As ATC,
ContactList.Id As IDIP,
ContactList1.Id As IDSP,
ContactList2.Id As IDA1,
ContactList3.Id As IDA2
From
Schedule Inner Join
StudentLesson On Schedule.ScheduleLessonID = StudentLesson.StudentLessonID
Inner Join
MasterLesson On StudentLesson.LessonID = MasterLesson.ID Inner Join
Equipment On Schedule.EquipmentID = Equipment.ID Left Join
CallSignList On CallSignList.ID = Schedule.CallSignListID Left Join
Route On Route.ID = Schedule.RouteID Inner Join
ContactList On ContactList.Id = Schedule.ContactIDIP Inner Join
ContactList ContactList1 On ContactList1.Id = Schedule.ContactIDSP
Left Join
ContactList ContactList2 On Schedule.ContactIDACM1 = ContactList2.Id
Left Join
ContactList ContactList3 On Schedule.ContactIDACM2 = ContactList3.Id
Left Join
Airport On Route.AirportID_Dep = Airport.ID Left Join
Airport Airport1 On Route.AirportID_Via = Airport1.ID Left Join
Airport Airport2 On Route.AirportID_Arr = Airport2.ID
Where
((Schedule.StatusRelease = 1) Or
(Schedule.StatusRequest = 1)) And
Schedule.ScheduleDay = '21.02.2014') As ST)
Select Distinct
STall.IDIP,SInfo
From
STall
where STall.IDIP > 0
UNION
Select Distinct
STall.IDSP,SInfo
From
STall
where STall.IDSP > 0
UNION
Select Distinct
STall.IDA1,SInfo
From
STall
where STall.IDA1 > 0
UNION
Select Distinct
STall.IDA2,SInfo
From
STall
where STall.IDA2 > 0
Now - I tried to add another With STtotal as ( in the beginning...
and
)
Select Distinct
STsub.IDIP,
SubString((Select
+Char(10) + STn1.SInfo As [text()]
From
STsub STn1
Where
STn1.IDIP = STtotal.IDIP
Order By
STn1.IDIP
For Xml Path('')), 2, 1000) ScheduleInfo
From
STtotal
But I get an error - with wrong Statement at "with".
Maybe there is another approach - how to combine - the "Info Text" column with all IDs - which could be in column 2-5.
Thanks for any imput
Separate your CTEs with a comma; the WITH only needs to be specified once:
;WITH CTE1 AS (
...
), CTE2 AS (
...
)
SELECT ...
Did you remember to put a semi colon at the end of the first statement?
Declare #alias as varchar(10)
set #alias = 'fk2'
insert into #Queries(Query, ExecuteOrder)
select top 1 'delete ' + fk1.TableFrom + ' from ' + fk1.TableFrom
+ ' join ' + #alias.TableFrom + ' on ' + fk1.TableFrom+'.'+fk1.FK_Column + ' = ' + fk2.TableFrom + '.ID'
+ ' join ' + fk3.TableFrom + ' on ' + fk2.TableFrom+'.'+fk2.FK_Column + ' = ' + fk3.TableFrom + '.ID'
+ ' join ' + fk4.TableFrom + ' on ' + fk3.TableFrom+'.'+fk3.FK_Column + ' = ' + fk4.TableFrom + '.ID'
+ ' Where ' + fk4.TableFrom + '.' + fk4.FK_Column + ' = ' + #value
,#i
from #FK fk1
join #fk As #alias on #alias.TableFrom = fk1.TableTo
join #fk fk3 on fk3.TableFrom = fk2.TableTo
join #fk fk4 on fk4.TableFrom = fk3.TableTo
I am joining a table to itself to build a resulting query to then be executed from the temp table being inserted into. I am currently specifying the amount of joins but would like to build them dynamically based on another integer value being passed in. The amount of joins will correlate with this integer value. The only problem is I need a unique Alias for each join to then be used above to build the resulting query. Is it possible to use a dynamic Alias as to eliminate the need to hardcode the Alias for each join?
My query has this structure:
SELECT DISTINCT (CO.CateringOrderId),
CO.CateringOrderNumber,
MC.FirstName + ' ' + MC.LastName AS "CustomerName",
CO.EventDate AS EventDate,
CO.IsCompleted,
CO.IsVerified,
MC.EmailId,
CAT.OfficePhone,
CAT.Mobile,
CAT.Fax,
CO.TotalInvoiceAmount,
CO.BarterCharityId,
(SELECT Sum (Amount)
FROM Catering_Order_Payment_Trans
WHERE CateringOrderId = CO.CateringOrderId) AS AmountReceived
FROM Catering_Orders CO,
Master_Customer MC,
Customer_Address_Trans CAT,
Catering_Order_Employee_Trans COET
WHERE MC.CompanyId = #p_CompanyId
AND (MC.CustomerId = #p_CustomerId OR #p_CustomerId = -1)
AND (CO.CateringOrderNumber LIKE '%' + #p_CateringOrderNumber + '%')
AND (CO.EventDate >= CONVERT (DATETIME, #p_FromDate) OR #p_FromDate = '')
AND (CO.EventDate <= CONVERT (DATETIME, #p_ToDate) OR #p_ToDate = '')
AND (CO.IsCompleted = #p_IsCompleted OR #p_IsCompleted = -1)
AND (COET.EmployeeId = #p_CatererId OR #p_CatererId = -1)
AND MC.CustomerId = CO.CustomerId
AND MC.PersonalAddressId = CAT.CustomerAddressId
AND (COET.CateringOrderId = CO.CateringOrderId
OR CO.CateringOrderId NOT IN
(SELECT CateringOrderId FROM Catering_Order_Employee_Trans))
AND (CAT.Mobile like '%' + #p_ContactNumber + '%' )
AND (CO.IsActive is null or CO.IsActive=1)
ORDER BY CO.CateringOrderId DESC
I think the SUM sub-query is slowing it. Please suggest me on how to speed it up.
Currently its execution time is around 7 - 10 seconds.
Try something like this -
SELECT DISTINCT
CO.CateringOrderId,
CO.CateringOrderNumber,
MC.FirstName + ' ' + MC.LastName AS CustomerName,
CO.EventDate AS EventDate,
CO.IsCompleted,
CO.IsVerified,
MC.EmailId,
CAT.OfficePhone,
CAT.Mobile,
CAT.Fax,
CO.TotalInvoiceAmount,
CO.BarterCharityId,
AmountReceived = (
SELECT SUM(t.Amount)
FROM dbo.Catering_Order_Payment_Trans t
WHERE t.CateringOrderId = CO.CateringOrderId
)
FROM (
SELECT *
FROM dbo.Catering_Orders
WHERE ISNULL(IsActive, 1) = 1
AND (IsCompleted = #p_IsCompleted OR #p_IsCompleted = -1)
AND CateringOrderNumber LIKE '%' + #p_CateringOrderNumber + '%'
AND EventDate BETWEEN
CONVERT(DATETIME, ISNULL(NULLIF(#p_FromDate, ''), '18000101'))
AND
CONVERT(DATETIME, ISNULL(NULLIF(#p_ToDate, ''), '30000101'))
) CO
JOIN dbo.Master_Customer MC ON MC.CustomerId = CO.CustomerId
JOIN dbo.Customer_Address_Trans CAT ON MC.PersonalAddressId = CAT.CustomerAddressId
LEFT JOIN (
SELECT *
FROM dbo.Catering_Order_Employee_Trans
WHERE EmployeeId = #p_CatererId
OR #p_CatererId = -1
) COET ON COET.CateringOrderId = CO.CateringOrderId
WHERE MC.CompanyId = #p_CompanyId
AND (MC.CustomerId = #p_CustomerId OR #p_CustomerId = -1)
AND CAT.Mobile LIKE '%' + #p_ContactNumber + '%'
The main problems in
AND (COET.CateringOrderId = CO.CateringOrderId
OR CO.CateringOrderId NOT IN
(SELECT CateringOrderId FROM Catering_Order_Employee_Trans))
and
(SELECT Sum (Amount)
FROM Catering_Order_Payment_Trans
WHERE CateringOrderId = CO.CateringOrderId) AS AmountReceived
Try:
SELECT CO.CateringOrderId,
CO.CateringOrderNumber,
MC.FirstName + ' ' + MC.LastName AS "CustomerName",
CO.EventDate AS EventDate,
CO.IsCompleted,
CO.IsVerified,
MC.EmailId,
CAT.OfficePhone,
CAT.Mobile,
CAT.Fax,
CO.TotalInvoiceAmount,
CO.BarterCharityId,
COPT.AmountReceived
FROM Catering_Orders CO
JOIN Master_Customer MC ON MC.CustomerId = CO.CustomerId
JOIN Customer_Address_Trans CAT ON MC.PersonalAddressId = CAT.CustomerAddressId
LEFT JOIN (SELECT CateringOrderId, Sum(Amount) AS AmountReceived
FROM Catering_Order_Payment_Trans
GROUP BY CateringOrderId) COPT
ON COPT.CateringOrderId = CO.CateringOrderId
WHERE MC.CompanyId = #p_CompanyId
AND (MC.CustomerId = #p_CustomerId OR #p_CustomerId = -1)
AND (CO.CateringOrderNumber LIKE '%' + #p_CateringOrderNumber + '%')
AND (CO.EventDate >= CONVERT (DATETIME, #p_FromDate) OR #p_FromDate = '')
AND (CO.EventDate <= CONVERT (DATETIME, #p_ToDate) OR #p_ToDate = '')
AND (CO.IsCompleted = #p_IsCompleted OR #p_IsCompleted = -1)
AND EXISTS
(SELECT NULL
FROM Catering_Order_Employee_Trans COET
WHERE COET.CateringOrderId = CO.CateringOrderId AND
(COET.EmployeeId = #p_CatererId OR #p_CatererId = -1) )
AND (CAT.Mobile like '%' + #p_ContactNumber + '%' )
AND (CO.IsActive is null or CO.IsActive=1)
ORDER BY CO.CateringOrderId DESC
To optimize your query you should edit the OR condition inserted inside AND conditions which really slow down your query
AND ( CO.EventDate <= CONVERT (DATETIME, #p_ToDate)
OR #p_ToDate = '')
should become something like
AND ( CO.EventDate <= CASE WHEN #p_ToDate = '' THEN
GETDATE()
ELSE
CONVERT (DATETIME,#p_ToDate)
END)
Also try to remove one by one the innested select both in select and in where to see which one most slows down the query