I want to optimize this query
WITH CTE AS
(
SELECT
KladrItemName _KladrItemName
, WordPositionKladrItem _WordPositionKladrItem
, WordPositionAddressString _WordPositionAddressString
, StartPosition _StartPosition
, EndPosition _EndPosition
, Metric _Metric
, IsConstruction _IsConstruction
, WordsCount _WordsCount
, Indeces _Indeces
, WordPositionAddressString _StartWordIndex
, WordPositionAddressString _EndWordIndex
, 1 _StepNumber
FROM
(
SELECT
dbo.tKladrItems.KladrItemName
, dbo.tFoundWords.WordFromAddressString
, dbo.tFoundWords.WordFromKladr
, dbo.tFoundWords.WordPosition AS WordPositionAddressString
, dbo.tWordKladrItems.wordNumber AS WordPositionKladrItem
, dbo.tFoundWords.StartPosition
, dbo.tFoundWords.EndPosition
, dbo.tFoundWords.Metric
, dbo.tFoundWords.IsConstruction
, dbo.tKladrItems.WordsCount
, dbo.tKladrItems.Indeces
FROM
dbo.tWordsFromKladr JOIN dbo.tWordKladrItems ON dbo.tWordsFromKladr.ID = dbo.tWordKladrItems.wordID
JOIN dbo.tFoundWords ON dbo.tFoundWords.WordFromKladr = dbo.tWordsFromKladr.WordFromKladr
JOIN dbo.tKladrItems ON dbo.tWordKladrItems.kladrItemID = dbo.tKladrItems.id
)T
UNION ALL
SELECT
KladrItemName
, WordPositionKladrItem
, WordPositionAddressString
, CASE WHEN StartPosition _EndPosition THEN EndPosition ELSE _EndPosition END -- MAX
, CAST(Metric + _Metric AS numeric(20, 10))
, IsConstruction + _IsConstruction
, WordsCount
, Indeces
, CASE WHEN _StartWordIndex WordPositionAddressString THEN _EndWordIndex ELSE WordPositionAddressString END
, 1 + _StepNumber
FROM
(
SELECT
dbo.tKladrItems.KladrItemName
, dbo.tFoundWords.WordFromAddressString
, dbo.tFoundWords.WordFromKladr
, dbo.tFoundWords.WordPosition AS WordPositionAddressString
, dbo.tWordKladrItems.wordNumber AS WordPositionKladrItem
, dbo.tFoundWords.StartPosition
, dbo.tFoundWords.EndPosition
, dbo.tFoundWords.Metric
, dbo.tFoundWords.IsConstruction
, dbo.tKladrItems.WordsCount
, dbo.tKladrItems.Indeces
FROM
dbo.tWordsFromKladr JOIN dbo.tWordKladrItems ON dbo.tWordsFromKladr.ID = dbo.tWordKladrItems.wordID
JOIN dbo.tFoundWords ON dbo.tFoundWords.WordFromKladr = dbo.tWordsFromKladr.WordFromKladr
JOIN dbo.tKladrItems ON dbo.tWordKladrItems.kladrItemID = dbo.tKladrItems.id
) AS Tab JOIN CTE ON
Tab.KladrItemName = CTE._KladrItemName
AND Tab.WordPositionKladrItem > CTE._WordPositionKladrItem
AND Tab.WordPositionAddressString > CTE._WordPositionAddressString
)
SELECT DISTINCT
_KladrItemName KladrItemName
, _StartPosition StartPosition
, _EndPosition EndPosition
, _Metric SumMetric
, _IsConstruction SumIsConstruction
, _Indeces Indeces
FROM
CTE
WHERE
_StepNumber = _WordsCount
AND (_IsConstruction = 0 or (_IsConstruction = 1 and _WordsCount > 1))
AND _EndWordIndex - _StartWordIndex + 1 = _WordsCount
option (maxrecursion 0)
So that the table
SELECT
dbo.tKladrItems.KladrItemName
, dbo.tFoundWords.WordFromAddressString
, dbo.tFoundWords.WordFromKladr
, dbo.tFoundWords.WordPosition AS WordPositionAddressString
, dbo.tWordKladrItems.wordNumber AS WordPositionKladrItem
, dbo.tFoundWords.StartPosition
, dbo.tFoundWords.EndPosition
, dbo.tFoundWords.Metric
, dbo.tFoundWords.IsConstruction
, dbo.tKladrItems.WordsCount
, dbo.tKladrItems.Indeces
FROM
dbo.tWordsFromKladr JOIN dbo.tWordKladrItems ON dbo.tWordsFromKladr.ID = dbo.tWordKladrItems.wordID
JOIN dbo.tFoundWords ON dbo.tFoundWords.WordFromKladr = dbo.tWordsFromKladr.WordFromKladr
JOIN dbo.tKladrItems ON dbo.tWordKladrItems.kladrItemID = dbo.tKladrItems.id
builds only once. But when I declare it as a temporary table, the execution time increases several times. Is there a way to optimize it by building this table once? Is there a way to optimaze it somehow else?
Thank you for help.
Use:
WITH base_table AS (
SELECT wki.KladrItemName,
fw.WordFromAddressString,
fw.WordFromKladr,
fw.WordPosition AS WordPositionAddressString,
tfk.wordNumber AS WordPositionKladrItem,
fw.StartPosition,
fw.EndPosition,
fw.Metric,
fw.IsConstruction,
wki.WordsCount,
wki.Indeces
FROM dbo.tWordsFromKladr tfk
JOIN dbo.tWordKladrItems wki ON wki.wordID = tkf.ID
JOIN dbo.tFoundWords fw ON fw.WordFromKladr = tfk.WordFromKladr
JOIN dbo.tKladrItems ki ON ki.id = wki.kladrItemID),
cte AS (
SELECT bt.*
FROM base_table bt
UNION ALL
SELECT KladrItemName,
WordPositionKladrItem,
WordPositionAddressString,
CASE WHEN StartPosition _EndPosition THEN EndPosition ELSE _EndPosition END -- MAX,
CAST(Metric + _Metric AS numeric(20, 10)),
IsConstruction + _IsConstruction,
WordsCount,
Indeces,
CASE WHEN _StartWordIndex WordPositionAddressString THEN _EndWordIndex ELSE WordPositionAddressString END,
1 + _StepNumber
FROM base_table)
...
You can create two CTEs in a statement. Try this:
WITH Sub As
(SELECT i.KladrItemName,
f.WordFromAddressString, f.WordFromKladr,
f.WordPosition WordPositionAddressString,
wi.wordNumber WordPositionKladrItem,
f.StartPosition, f.EndPosition, f.Metric,
f.IsConstruction, i.WordsCount, i.Indeces
FROM dbo.tWordsFromKladr w
JOIN dbo.tWordKladrItems wi ON wi.ID = i.wordID
JOIN dbo.tFoundWords f ON f.WordFromKladr = w.WordFromKladr
JOIN dbo.tKladrItems i ON wi.kladrItemID = i.id ),
CTE As
(SELECT KladrItemName _KladrItemName,
WordPositionKladrItem _WordPositionKladrItem,
WordPositionAddressString _WordPositionAddressString,
StartPosition _StartPosition ,
EndPosition _EndPosition,
Metric _Metric, IsConstruction _IsConstruction,
WordsCount _WordsCount,
Indeces _Indeces,
WordPositionAddressString _StartWordIndex ,
WordPositionAddressString _EndWordIndex,
1 _StepNumber
FROM Sub T
UNION ALL
SELECT KladrItemName, WordPositionKladrItem, WordPositionAddressString,
CASE WHEN StartPosition < _EndPosition
THEN EndPosition ELSE _EndPosition END, -- Max
CAST(Metric + _Metric AS numeric(20, 10)),
IsConstruction + _IsConstruction,
WordsCount, Indeces,
CASE WHEN _StartWordIndex WordPositionAddressString
THEN _EndWordIndex ELSE WordPositionAddressString END,
1 + _StepNumber
FROM Sub Tab
JOIN CTE
ON Tab.KladrItemName = CTE._KladrItemName
AND Tab.WordPositionKladrItem > CTE._WordPositionKladrItem
AND Tab.WordPositionAddressString > CTE._WordPositionAddressString)
SELECT DISTINCT _KladrItemName KladrItemName,
_StartPosition StartPosition, _EndPosition EndPosition,
_Metric SumMetric,_IsConstruction SumIsConstruction,
_Indeces Indeces
FROM CTE
WHERE_StepNumber = _WordsCount
AND (_IsConstruction = 0 or (_IsConstruction = 1 and _WordsCount > 1))
AND _EndWordIndex - _StartWordIndex + 1 = _WordsCountoption
(maxrecursion 0)
Related
I have a view from the view need to fetch some result set for that purpose I have wrote following query.
So here the problem is stuff with xml is taking so much time any suggestions please.
;WITH CTE_transaction_type1 AS
(
SELECT case_summary_id,Primary_Payer, Physician,Generate_Bill,
CASE
WHEN Current_Payer IS NULL
THEN CASE
WHEN Resposible_Patient_Name IS NULL
AND PG_Patient_Name IS NULL
THEN 'PG:' + Patient_Last_Name + ',' + Patient_First_Name
WHEN Resposible_Patient_Name IS NULL
AND NULLIF(PG_Patient_Name,' ') IS NOT NULL
THEN 'SG:' + Patient_Last_Name + ',' + Patient_First_Name
ELSE Resposible_Patient_Name
END
ELSE
CASE
WHEN Current_Payer_Name IS NULL
THEN ''
ELSE Insurance_Type + Current_Payer_Name + IIF(Plan_Name IS NULL, '', ',' + Plan_Name)
END
END AS Responsible_Party_List
FROM [charts].[vw_billing_analysis]
WHERE sort_order = 0 AND transaction_type_id = 1
)
SELECT ba.Case_Summary_ID
,ba.date_of_surgery
,ba.Organization_ID
,ba.Organization_Name
,ba.Patient_Name
,ba.Patient_First_Name
,ba.Patient_Last_Name
,ba.MRN
,ba.Physician_ID
,ba.Physician
,ba.[PROCEDURE]
,ba.Current_Payer
,ba.Current_Payer_Name
,ba.Primary_Payer
,ba.Primary_Payer_ID
,ba.Insurance_Plan_ID
,ba.Insurance_Plan_Type
,ba.Plan_Name
,ba.Speciality_ID
,ba.Speciality_Name
,ba.Transaction_Responsible_Party_ID
,ba.Charge_ID
,ba.Charge_Procedure_ID
,ba.Patient_Insurance_ID
,ba.Insurance_Type
,ba.Resposible_Patient_Name
,ba.Received_From
,ba.Guarantor_Master_ID
,ba.PG_Patient_Name
,ba.Batch_Description
,ba.Period_Name
,ba.Unassigned_payment
,ba.Charge
,ba.Charge_Corr
,ba.Debit
,ba.Payments
,ba.WriteOff
,ba.Balance
,ba.Corrected_TF
,ba.Period_ID
,ba.Batch_ID
,ba.transaction_type_id
,STUFF((
SELECT '; ' + [Procedure]
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
AND vba.transaction_type_id = 1
ORDER BY ba.sort_order
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 2, '') AS Procedure_List
,trty1.Primary_Payer AS Primary_Payer_List
,trty1.Responsible_Party_List
,trty1.Physician AS Physician_List
,ba.Allowed_Amount
,IIF(ba.insurance_contract_id IS NULL
OR ba.Insurance_Plan_Type = 'Self-Pay', NULL, iif(ba.procedure_type IS NOT NULL, round(ba.[allowed_amount] - (ba.[allowed_amount] * ba.procedure_discount / 100.0), 3), ba.[procedure_amount])) AS [Expected_Amount]
,ba.Procedure_Amount
,ba.Generate_Bill
,trty1.Generate_Bill AS Generate_Bill_Case
,ba.Actual_Payment
,ba.First_Bill_Date
FROM [charts].[vw_billing_analysis] ba
left join cte_transaction_type1 trty1
ON ba.Case_Summary_ID=trty1.Case_Summary_ID
WHERE ba.Organization_ID =52
AND
(
(
(
(
ba.Period_Id = ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
AND (
(
ba.Batch_Id IN ('999999999')
OR '999999999' = '999999999'
)
AND 0 = 1
)
)
OR (
0 = 0
AND ba.date_of_surgery >= '2018-02-01'
AND ba.date_of_surgery <= '2021-03-03'
)
)
AND (
CASE
WHEN ba.Insurance_Plan_Type IS NULL
AND ba.Insurance_Plan_ID IS NULL
AND ba.Current_Payer IS NULL
THEN '-1'
ELSE ba.Insurance_Plan_Type_Id
END IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Current_Payer IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Speciality_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.Physician_ID IN ('999999999')
OR '999999999' = '999999999'
)
AND (
isnull(ba.Primary_Payer_ID, - 1) IN ('999999999')
OR '999999999' = '999999999'
)
AND (
ba.appointment_type_id IN ('999999999')
OR '999999999' = '999999999'
)
AND (
SELECT SUM(CASE
WHEN vba.transaction_type_id = 1
THEN balance
WHEN vba.transaction_type_id = 3
THEN - balance
END)
FROM [charts].[vw_billing_analysis] vba
WHERE vba.case_summary_id = ba.case_summary_id
) >= 0
ORDER BY ba.Date_Of_Surgery DESC
,ba.MRN DESC
,ba.Patient_Name ASC
,ba.upd_tr_sort ASC
,ba.Sort_Order ASC
I have a stored procedures with three different queries, that querys return values depending of received variable.
They basically return same data, just change WHERE clauses:
Query:
IF #DesignType = 'BDCD'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND ([DT].[DesignTypeGuid] != IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument))
AND [DT].[DesignTypeGuid] != #ChangeOrder
AND [DT].[DesignTypeGuid] != #AddedPart
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'CO'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #ChangeOrder
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'AP'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #AddedPart
ORDER BY
[DT].[Order]
END
Is there any way to optimize this and do it in a simple SELECT instead do 3 differents depending of DesignType variable? Regards
Not sure about the performance , but the query could definitely be written as
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CASE #DesignType WHEN 'BDCD' THEN CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) ELSE 0 END AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND (
(
#DesignType = 'BDCD' AND [DT].[DesignTypeGuid] NOT IN ( IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument),#ChangeOrder,#AddedPart)
)
OR
(
#DesignType = 'CO' AND [DT].[DesignTypeGuid] = #ChangeOrder
)
OR
(
#DesignType = 'AP' AND [DT].[DesignTypeGuid] = #AddedPart
)
)
ORDER BY
[DT].[Order]
When I'm trying to convert this piece of SQL to LINQ, I received this error:
SQL cannot be converted to LINQ: Table [GL] not found in the current
Data Context.
But in SQL it works fine.
This is my SQL query:
SELECT itm.Id ,
ISNULL(itm.Debit, 0) AS Debit ,
ISNULL(itm.Credit, 0) AS Credit ,
itm.State ,
itm.DocCreateDate ,
ISNULL(itm.Num, 0) AS Num ,
ISNULL(itm.DocTypeRef, 0) AS DocTypeRef ,
itm.Year ,
itm.Month ,
ISNULL(itm.DebitCount, 0) AS DebitCount ,
ISNULL(itm.CreditCount, 0) AS CreditCount ,
itm.DL ,
itm.DL2 ,
itm.DL3 ,
itm.DL4 ,
itm.DL5 ,
itm.DL6 ,
itm.DL7 ,
ISNULL(itm.FCRef, 0) AS FCRef ,
itm.FollowUpNum ,
ISNULL(itm.BranchRef, 1) AS BranchRef ,
itm.DocHeaderRef ,
ISNULL(itm.RowNum, 0) AS RowNum ,
ISNULL(itm.DailyNum, 0) AS DailyNum ,
ISNULL(itm.TempNum, 0) AS TempNum ,
ISNULL(itm.RefNum, 0) AS RefNum ,
itm.Descript ,
itm.Count ,
itm.FollowUpDate ,
itm.FCVal ,
itm.FCRateVal ,
itm.FactorNum ,
ISNULL(itm.DebitFCVal, 0) AS DebitFCVal ,
ISNULL(itm.CreditFCVal, 0) AS CreditFCVal ,
sl.Id AS SLRef ,
sl.SLCode ,
sl.Title AS SLTitle ,
CASE WHEN ISNULL(sl.DLSRef, 0) > 0 THEN 1
ELSE 0
END AS HasDL ,
CASE WHEN ISNULL(sl.DLSRef2, 0) > 0 THEN 1
ELSE 0
END AS HasDL2 ,
CASE WHEN ISNULL(sl.DLSRef3, 0) > 0 THEN 1
ELSE 0
END AS HasDL3 ,
CASE WHEN ISNULL(sl.DLSRef4, 0) > 0 THEN 1
ELSE 0
END AS HasDL4 ,
CASE WHEN ISNULL(sl.DLSRef5, 0) > 0 THEN 1
ELSE 0
END AS HasDL5 ,
CASE WHEN ISNULL(sl.DLSRef6, 0) > 0 THEN 1
ELSE 0
END AS HasDL6 ,
CASE WHEN ISNULL(sl.DLSRef7, 0) > 0 THEN 1
ELSE 0
END AS HasDL7 ,
CASE WHEN ISNULL(sl.HasFC, 0) > 0 THEN 1
ELSE 0
END AS HasFC ,
1 AS HasFollow ,
tl.Id AS TLRef ,
tl.Title AS TLTitle ,
tl.TLCode ,
gl.Id AS GLRef ,
gl.Title AS GLTitle ,
gl.GLCode ,
gl.Balance AS GLBalance
FROM Acc.DocItem AS itm
LEFT OUTER JOIN Acc.SL AS sl ON itm.SLRef = sl.Id
LEFT OUTER JOIN Acc.TL AS tl ON sl.TLRef = tl.Id
LEFT OUTER JOIN Acc.GL AS gl ON tl.GLRef = gl.Id
WHERE ( itm.SLRef > 0 )
If there is no way to pass this error so can you tell me its LINQ equal?
There is a way to do that in linq:
var q =
from c in categories
join p in products on c.Category equals p.Category into ps
from p in ps.DefaultIfEmpty()
select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
This is the big idea for left outer join, you as the syntax for 'into' like 'as' in SQL query.
Could anyone please suggest what is the error in the below query? Actually I want to remove all duplicates from the select query output and fetch only unique rows. Thanks in advance.
select *
from (
select ROW_NUMBER() over (
partition by Dep
, tariffkode
, LinkTariffType
, poliata
, poliatavia
, podiata
, podiatavia
, PreCarriage
, PortTerminalId
, Product
, RoutingOrder
, PrepaidCollect
, isnull(description, '')
, ScaleCalcCode
, isnull(scalefrom, 0)
, isnull(scaleto, 0)
, CurrencyCode
, Base order by LinkTariffType desc
) Record
, *
from (
select tn.LinkTariffType
, tn.Dep
, tn.POLIata
, tn.POLIatavia
, tn.PODIata
, tn.PODIatavia
, tn.CurrencyCode
, tn.LegalEntityID
, tn.Rate
, tn.Base
, tn.Minimum
, tn.NrDescription
, tn.Description
, tn.DateFrom
, tn.DateUntil
, tn.DateCreate
, tn.DateMod
, tn.ModName
, tn.Tariffkode
, tn.ExpiryDate
, tn.PClass
, tn.Maximum
, tn.RoutingOrder
, tn.TariffCompType
, tn.PrePaidCollect
, tn.Product
, tn.IsDeleted
, (
select distinct Location_IATA
from Company
where Called = 'KARL KING'
and LegalEntityID = 1
and IsDeleted = 0
) as PreCarriage
, tn.PortTerminalID
, tn.ScaleFrom
, tn.ScaleTo
, tn.ScaleCalcCode
, tn.Mandatory
, (
select CompanyID
from PlaceOfReceipt
where warehouse = 'KARL KING'
and LegalEntityID = 1
and OfficeID = 13
and IsDeleted = 0
) as WarehouseID
, tn.TariffRelID
, tn.FreeDescription
, 0
, tn.ShipCode
, tn.AgentID
, tn.ContainerTypeID
, tn.CommodityID
, 0 as TempTable
from TariffNew tn
inner join hhInvoiceLines inv
on tn.Tariffkode = inv.NrInvoiceLine
where (
tn.PreCarriage is not null
and tn.PreCarriage != ''
)
and (
tn.POLIata is not null
and tn.POLIata != ''
)
and inv.OfficeID = 13
and inv.IsDeleted = 0
and inv.LegalEntityID = 1
and tn.LegalEntityID = 1
and tn.Dep = 'E'
and tn.IsDeleted = 0
and tn.DateUntil = '2078-12-31 00:00:00'
and tn.Description = 'kgl'
)
) as b
where b.Record = 1
First, you have to define what you want to call "unique rows".
Once you have the set of columns that determines a row is unique, that is the set of columns you use in the partition by part of row_number()
In the code below, uncomment the column set that defines your "unique rows":
select *
from (
select ROW_NUMBER() over (
partition by
Dep
--, tariffkode
--, LinkTariffType
--, poliata
--, poliatavia
--, podiata
--, podiatavia
--, PreCarriage
--, PortTerminalId
--, Product
--, RoutingOrder
--, PrepaidCollect
--, isnull(description, '')
--, ScaleCalcCode
--, isnull(scalefrom, 0)
--, isnull(scaleto, 0)
--, CurrencyCode
--, Base
order by LinkTariffType desc
) Record
, *
from (
select tn.LinkTariffType
, tn.Dep
, tn.POLIata
, tn.POLIatavia
, tn.PODIata
, tn.PODIatavia
, tn.CurrencyCode
, tn.LegalEntityID
, tn.Rate
, tn.Base
, tn.Minimum
, tn.NrDescription
, tn.Description
, tn.DateFrom
, tn.DateUntil
, tn.DateCreate
, tn.DateMod
, tn.ModName
, tn.Tariffkode
, tn.ExpiryDate
, tn.PClass
, tn.Maximum
, tn.RoutingOrder
, tn.TariffCompType
, tn.PrePaidCollect
, tn.Product
, tn.IsDeleted
, (
select distinct Location_IATA
from Company
where Called = 'KARL KING'
and LegalEntityID = 1
and IsDeleted = 0
) as PreCarriage
, tn.PortTerminalID
, tn.ScaleFrom
, tn.ScaleTo
, tn.ScaleCalcCode
, tn.Mandatory
, (
select CompanyID
from PlaceOfReceipt
where warehouse = 'KARL KING'
and LegalEntityID = 1
and OfficeID = 13
and IsDeleted = 0
) as WarehouseID
, tn.TariffRelID
, tn.FreeDescription
, 0 as UnnamedColumn
, tn.ShipCode
, tn.AgentID
, tn.ContainerTypeID
, tn.CommodityID
, 0 as TempTable
from TariffNew tn
inner join hhInvoiceLines inv on tn.Tariffkode = inv.NrInvoiceLine
where tn.PreCarriage is not null
and tn.PreCarriage != ''
and tn.POLIata is not null
and tn.POLIata != ''
and inv.OfficeID = 13
and inv.IsDeleted = 0
and inv.LegalEntityID = 1
and tn.LegalEntityID = 1
and tn.Dep = 'E'
and tn.IsDeleted = 0
and tn.DateUntil = '2078-12-31 00:00:00'
and tn.Description = 'kgl'
) as s
) as b
where b.Record = 1
I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.