Returning column with count of 0 - sql

I have a query that looks up a list of documents depending on their department and their status.
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.name,
COUNT(*) AS TodayCount
FROM dbo.TableA ILDP
LEFT JOIN dbo.TableB ILDPS ON ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId
LEFT JOIN dbo.TableC ILDPST ON ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId
WHERE (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
AND ILDPS.CurrentStateTypeId IN (
SELECT value
FROM dbo.StringAsIntTable(#StatusIds)
)
GROUP BY ILDPST.name;
This returns the results:
However, I'd also like to be able to return statuses where the TodayCount is equal to 0 (i.e. any status with an id included in #StatusIds should be returned, regardless of TodayCount).
I've tried messing with some unions / joins / ctes but I couldn't quite get it to work. I'm not much of an SQL person so not sure what else to provide that could be useful.
Thanks!

If you want to have all the records from TableC you need to left join all other tables to it, not left join it to the other tables. Also it's best to INNER JOIN the filtering table you create from #StatusIds rather then apply it through INclause. Try this:
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.Name, COUNT(ILDP.IntranetLoanDealPreStateId) AS TodayCount
FROM (SELECT DISTINCT value FROM dbo.StringAsIntTable(#StatusIds)) StatusIds
INNER JOIN dbo.TableC ILDPST
ON ILDPST.IntranetLoanDealPreStateTypeId = StatusIds.value
LEFT JOIN dbo.TableB ILDPS
ON ILDPS.CurrentStateTypeId = ILDPST.IntranetLoanDealPreStateTypeId
LEFT JOIN dbo.TableA ILDP
ON ILDP.IntranetLoanDealPreStateId = ILDPS.IntranetLoanDealPreStateId
AND (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
GROUP BY ILDPST.Name;

Try this instead:
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
DECLARE #DepartmentId NVARCHAR(2) = 'IT';
SELECT ILDPST.name,
COUNT(ILDP.IntranetLoanDealPreStateId) AS TodayCount
FROM
dbo.TableC ILDPST
LEFT JOIN
dbo.TableB ILDPS ON ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId
LEFT JOIN
dbo.TableA ILDP ON ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId
AND (ILDP.CreatedByDepartmentId = #DepartmentId OR #DepartmentId IS NULL)
WHERE
ILDPST.IntranetLoanDealPreStateTypeId
IN (
SELECT value
FROM dbo.StringAsIntTable(#StatusIds)
)
GROUP BY ILDPST.name;

You could use the following function to create a table value for your status id's.
CREATE FUNCTION [dbo].[SplitString]
(
#myString varchar(max),
#deliminator varchar(2)
)
RETURNS
#ReturnTable TABLE
(
[Part] [varchar](max) NULL
)
AS
BEGIN
Declare #iSpaces int
Declare #part varchar(max)
--initialize spaces
Select #iSpaces = charindex(#deliminator,#myString,0)
While #iSpaces > 0
Begin
Select #part = substring(#myString,0,charindex(#deliminator,#myString,0))
Insert Into #ReturnTable(Part)
Select #part
Select #myString = substring(#mystring,charindex(#deliminator,#myString,0)+ len(#deliminator),len(#myString) - charindex(' ',#myString,0))
Select #iSpaces = charindex(#deliminator,#myString,0)
end
If len(#myString) > 0
Insert Into #ReturnTable
Select #myString
RETURN
END
This can now be used as a table that you can LEFT JOIN to.
DECLARE #StatusIds NVARCHAR(MAX) = '1,2,3,4,5';
SELECT * FROM dbo.SplitString(#StatusIds, ',')

It is not tested but give it a try:
;With Cte ( Value ) As
( Select Distinct Value From dbo.StringAsIntTable( #StatusIds ) )
Select
ILDPST.name,
COUNT(*) AS TodayCount
From
dbo.TableC As ILDPST
Inner Join Cte On ( ILDPST.IntranetLoanDealPreStateTypeId = Cte.Value )
Left Join dbo.TableB As ILDPS On ( ILDPST.IntranetLoanDealPreStateTypeId = ILDPS.CurrentStateTypeId )
Left Join dbo.TableA As ILDP On ( ILDPS.IntranetLoanDealPreStateId = ILDP.IntranetLoanDealPreStateId )
And ( ( ILDP.CreatedByDepartmentId = #DepartmentId ) Or ( #DepartmentId Is Null ) )
Group By
ILDPST.name

Related

Offer to increase performance in stored procedure

I write this query in SQL Server 2016:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[s2_GetReceivedDocumentsCount]
#_Username NVARCHAR(MAX),
#_SearchText NVARCHAR(MAX),
#_States NVARCHAR(MAX),
#_Senders NVARCHAR(MAX),
#_Date1 NVARCHAR(MAX),
#_Date2 NVARCHAR(MAX),
#_Filter1ID NVARCHAR(MAX),
#_Filter1Value NVARCHAR(MAX)
AS
BEGIN
--https://blogs.technet.microsoft.com/mdegre/2011/11/06/what-is-parameter-sniffing/
DECLARE #Username NVARCHAR(MAX)
DECLARE #Fild BIT
DECLARE #SearchText NVARCHAR(MAX)
DECLARE #States NVARCHAR(MAX)
DECLARE #Senders NVARCHAR(MAX)
DECLARE #Date1 NVARCHAR(MAX)
DECLARE #Date2 NVARCHAR(MAX)
DECLARE #Filter1ID NVARCHAR(MAX)
DECLARE #Filter1Value NVARCHAR(MAX)
SELECT
#Username = #_Username,
#SearchText = #_SearchText,
#States = #_States,
#Senders = #_Senders,
#Date1 = #_Date1,
#Date2 = #_Date2,
#Filter1ID = #_Filter1ID,
#Filter1Value = #_Filter1Value
SELECT #SearchText = LTRIM(RTRIM(IsNull(#SearchText, '')))
SELECT #Filter1ID = LTRIM(RTRIM(IsNull(#Filter1ID, '')))
SELECT #Filter1Value = LTRIM(RTRIM(IsNull(#Filter1Value, '')))
DECLARE #PersonalPostID INT = NULL
SELECT #PersonalPostID = p.PostID
FROM Person pr
JOIN PersonPost pp ON pp.PersonID = pr.PersonID
JOIN Post p ON p.PostID = pp.PostID
WHERE pr.Username = #Username
AND p.IsPersonalPost = 1
DECLARE #independentPostExists BIT = CASE
WHEN EXISTS (SELECT 1 FROM Post t
WHERE t.Independent = 1 AND t.PostID > 0)
THEN 1
ELSE 0
END
DECLARE #temp0 TABLE (
DocumentID int
, Likeness int
, ParentScrutinyID int
)
;With AllPost
As
(
Select pp.PostID
From
PersonPost pp
Join Person prs On prs.PersonID = pp.PersonID
Where prs.Username = #Username
Union
Select [type].PostID
From
Post [type]
Join Post p On p.TypeID = [type].PostID
Join PersonPost pp On pp.PostID = p.PostID
Join Person prs On prs.PersonID = pp.PersonID
Where prs.Username = #Username
)
,
SplitSearchText
AS
(
Select * From dbo._1001_Split(dbo.ReplaceYK(#SearchText),N'')
),
Temp0
AS
(
Select Distinct
s.DocumentID
, s.Code
, s2_Scrutiny.ParentScrutinyID
From
s2_Document s
Join s2_State state On state.StateID = s.StateID
Join Post sender On sender.PostID = s.SenderID
Join s2_Scrutiny On
s2_Scrutiny.DocumentID = s.DocumentID
And s2_Scrutiny.IsActive = 1
And s2_Scrutiny.ReferenceID not in (-10, -20)
Cross Join AllPost
Join s2_Producer On s2_Producer.DocumentID = s.DocumentID
Join PersonPost producerPost On producerPost.PostID = s2_Producer.PostID
Join Person producerPerson On producerPerson.PersonID = producerPost.PersonID
Where
1 = 1
And (#States = '' Or (N',' + #States + N',') Like (N'%,' + Cast(s.StateID as nvarchar(max)) + ',%'))
And (#Senders = '' Or (N',' + #Senders + N',') Like (N'%,' + Cast(s.SenderID as nvarchar(max)) + ',%'))
And (#Date1 = '' Or s.RegistrationDate >= #Date1)
And (#Date2 = '' Or s.RegistrationDate <= #Date2)
And (#Filter1ID = ''
Or Exists(
Select 1
From
s2_FieldValue fv
Join s2_Field f On f.FieldID = fv.FieldID
Where
fv.DocumentID = s.DocumentID
And fv.FieldID = #Filter1ID
And (
(f.FieldTypeID in (0, 5/*فیلد محاسباتی*/) And fv.[Value] = #Filter1Value)
Or (f.FieldTypeID = 3 And Cast(fv.[FieldOptionID] as nvarchar(max)) = #Filter1Value)
Or (f.FieldTypeID in(1,2,4))
)
))
--پیشنهاد به پست یا نوع پستی که این شخص حائز آن است، ارجاع شده است
And AllPost.PostID = s2_Scrutiny.ReferenceID
), Temp1
AS
(
Select Distinct
s.DocumentID
,Likeness = 99999999
From Temp0 s
Where #SearchText != '' And #SearchText = ISNULL(s.Code, s.DocumentID)
Union
Select Distinct
s.DocumentID
,Likeness = SUM(ts.[Length])
From
Temp0 s
Join s2_TextSegment ts On
ts.TableName = N's2_Document'
And ts.FieldName = N'Subject'
And ts.RecordID = s.DocumentID
Where #SearchText != '' And #SearchText != ISNULL(s.Code, s.DocumentID)
Group by s.DocumentID
Union
Select Distinct
s.DocumentID
,Likeness = 1
From Temp0 s
Where #SearchText = ''
)
, Temp2
AS
(
Select t0.*, t1.Likeness
From
Temp0 t0
Join Temp1 t1 On t0.DocumentID = t1.DocumentID
)
Insert Into #temp0 (DocumentID, Likeness, ParentScrutinyID)
Select DocumentID, Likeness, ParentScrutinyID From Temp2
DECLARE #temp1 TABLE (
DocumentID int
, Likeness int
)
If #independentPostExists = 0
Begin
Insert Into #temp1 (DocumentID, Likeness)
Select
t.DocumentID
, t.Likeness
From
#temp0 t
End
ELSE
Begin--حوزه مستقلی تعریف شده باشد
--انتقال حوزه فعال باشد
Insert Into #temp1 (DocumentID, Likeness)
Select
t.DocumentID
, t.Likeness
From
#temp0 t
Join s2_Scrutiny parentScrutiny On parentScrutiny.ScrutinyID = t.ParentScrutinyID
Join s2_ScrutinyItem sci On sci.ScrutinyItemID = parentScrutiny.ScrutinyItemID
Where
sci.TransferArea = 1
-- شخص جاری در حوزه ارجاع دهنده باشد
Insert Into #temp1 (DocumentID, Likeness)
Select
t.DocumentID
, t.Likeness
From
#temp0 t
Join s2_Scrutiny parentScrutiny On parentScrutiny.ScrutinyID = t.ParentScrutinyID
Join Temp_SubalternPost tsp1 On tsp1.Subaltern_PostID = parentScrutiny.ScrutinierID
Join Temp_SubalternPost tsp2 On tsp2.Superior_PostID = tsp1.Superior_PostID
Where
tsp1.Superior_NearestIndependent = 1
And tsp2.Subaltern_PostID = #PersonalPostID
--And Not Exists(Select 1 From #temp0 tt Where tt.DocumentID = t.DocumentID)
End
Select Count(Distinct t.DocumentID) From #temp1 t Where Likeness > 0
END--end procedure
GO
This code takes 26 seconds:
exec sp_executesql N'Exec [dbo].[s2_GetReceivedDocumentsCount] #username=N'admin', #Filter1ID=N'12',#Filter1Value=N'17658'
BUT :
I tested this code for another state but returned 22,000 records in 3 seconds
exec sp_executesql N'Exec [dbo].[s2_GetReceivedDocumentsCount] #username=N'admin'
In this code I removed the #Filter1ID=N'12',#Filter1Value=N'17658'
When I remove this #Filter1ID it not enter here:
And (#Filter1ID = ''
Or Exists(
Select 1
From
s2_FieldValue fv
Join s2_Field f On f.FieldID = fv.FieldID
Where
fv.DocumentID = s.DocumentID
And fv.FieldID = #Filter1ID
And (
(f.FieldTypeID in (0, 5/*فیلد محاسباتی*/) And fv.[Value] = #Filter1Value)
Or (f.FieldTypeID = 3 And Cast(fv.[FieldOptionID] as nvarchar(max)) = #Filter1Value)
Or (f.FieldTypeID in(1,2,4))
)
))
Now I'm sure problem is here. But where is it? Where is the problem?
While correlated EXISTS clauses can be a real problem, your overall SP is such a dogs breakfast that I think you should focus on other aspects first:
Do not use LIKE to match a list of numeric values:
(N',' + #States + N',') Like (N'%,' + Cast(s.StateID as nvarchar(max)) + ',%'))
Since you already utilise string splitting function, you should split input value into a table variable of stateIDs (make sure that data type is the same as s.StateID and join it. Do the same for #Senders.
Minimise the use of OR as this kills performance really quickly:
This And (#Date1 = '' Or s.RegistrationDate >= #Date1) should be replaced by:
SET #Date1 = CASE WHEN '' THEN '01-Jan-1753' ELSE #Date1 END and then in your query you can simply have And s.RegistrationDate >= #Date1.
For #Date2 use the maximum value as per DATETIME reference.
Get rid of NVARCHAR( MAX ). Unless you realistically expect input values to be more than 4000 characters, you should use NVARCHAR( 2000 ) or something smaller.
There is a major performance difference between UNION and UNION ALL. Make sure you use UNION ALL unless you need to remove duplicate records. See this
And lastly EXISTS: without fully knowing your table structure and being able to run the query myself I cannot see a way of removing it, such that it will definitely improve performance.

Outer apply with INSERT statement

I want to do something like this
CREATE TABLE #tempFacilitiesAssociated
(
FacilityID BIGINT,
FacilityName VARCHAR(MAX),
IsPrimary BIT
)
-- Insert statements for procedure here
;WITH CTE_RESULT AS
(
SELECT
usr_id, t.name AS Title,
usr_fname, usr_lname, primaryAddress.add_suburb,
CASE
WHEN primaryAddress.add_suburb = #suburb THEN 1
WHEN t.name = #Title THEN 2
ELSE 3
END AS MatchOrder
FROM
core_users u
LEFT JOIN
RIDE_ct_title t ON t.title_id = u.usr_title
OUTER APPLY
(INSERT INTO #tempFacilitiesAssociated
EXEC dbo.[sp_Common_Get_AllFacilitiesForSupervisor] usr_id, 5
SELECT TOP 1 fa.*
FROM CORE_Facilities f
LEFT JOIN CORE_FacilityAddresses fa ON fac_id = fa.add_owner
WHERE fac_id = (SELECT TOP 1 FacilityID
FROM #tempFacilitiesAssociated
WHERE IsPrimary = 1)) primaryAddress
WHERE
u.usr_fname = #FirstName AND usr_lname = #LastName
)
So, first I want to get all facilities of that user through a stored procedure, and then use it to outer apply and select its suburb
UPDATE
I tried using function instead
CREATE FUNCTION fn_GetAddressForUserFacility
(#UserID BIGINT)
RETURNS #Address TABLE (FacilityID BIGINT,
add_address NVARCHAR(MAX),
add_addressline2 NVARCHAR(MAX),
add_suburb NVARCHAR(MAX)
)
AS
BEGIN
DECLARE #FacilitiesAssociated TABLE
(FacilityID BIGINT,
FacilityName NVARCHAR(MAX),
IsPrimary BIT)
INSERT INTO #FacilitiesAssociated
EXEC dbo.[sp_Common_Get_AllFacilitiesForSupervisor] #UserID, 5
INSERT INTO #Address
SELECT TOP 1
fa.add_owner, fa.add_address, fa.add_addressline2, fa.add_suburb
FROM
CORE_Facilities f
LEFT JOIN
CORE_FacilityAddresses fa ON f.fac_id = fa.add_owner AND add_type = 5
WHERE
fac_id = (SELECT TOP 1 FacilityID
FROM #FacilitiesAssociated
WHERE IsPrimary = 1)
RETURN
END
But now its returning
Invalid use of a side-effecting operator 'INSERT EXEC' within a function.

Changing SQL Stored Procedure for multiple search results

I have some inherited code I need to modify in order to accommodate multiple #ParentFolderID parameter. At present, one ID is passed in. However I will now need to account for several ID's being passed in and returning results from each. Below is the current code. I'm not quite sure what exactly where I would start.
declare #Values xml
declare #ValueAttributeID int
declare #YearAttributeID int
declare #CategoryID int
declare #year int
declare #ParentFolderID int
declare #DealerAttributeID int
set #ParentFolderID = 10646615
set #CategoryID = 10646175
set #YearAttributeID = 3
set #ValueAttributeID = 2
set #year = 2014
set #Values = '<values><value id=''1000104'' /></values>'
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
with Parents
(
dataid
)
as
(
select #ParentFolderID
Union
select child.dataid
from DTree parent (NOLOCK)
inner join DTree child (NOLOCK)
on parent.dataid = child.parentid
where parent.dataid = #ParentFolderID
and child.subtype = 0
)
select doc.name as '#name',
doc.dataId as '#id',
(
select allAtts.AttrID as '#id',
case when ((allAtts.ValInt is null) and (allAtts.ValStr is null))
then cast(allAtts.ValDate as nvarchar(255))
when (allAtts.ValInt is null and allAtts.ValDate is null)
then cast(allAtts.ValStr as nvarchar(255))
when (allAtts.ValDate is null and allAtts.ValStr is null)
then cast(allAtts.ValInt as nvarchar(255))
end as '#val'
from LLAttrData allAtts (NOLOCK)
where allAtts.id = doc.dataid
for xml path('attribute'), TYPE
)
from DTree category (NOLOCK)
inner join LLAttrData value (NOLOCK)
on category.dataid = value.defid
--Changes per environment (value attribute)
and value.AttrID = #ValueAttributeID
--Check for values
inner join #Values.nodes('//value') as A(att)
on A.att.value('#id', 'nvarchar(255)') = value.ValStr
--Changes per environment (year attribute)
inner join LLAttrData y (NOLOCK)
on category.dataid = y.defid
--Changes per environment (year attribute)
and y.AttrID = #YearAttributeID
--Check for year
and year(y.valDate) = #year
inner join DTree doc (NOLOCK)
on value.id = doc.dataid
and y.id = doc.dataid
inner join Parents parent
on parent.dataid = doc.parentid
--Must be associated to the category
where category.dataid = #CategoryID -- This is the hard coded category ID
order by doc.dataid --, allAtts.AttrID
FOR XML PATH('document'), Root('documents')`

passing multiple varchar values to parameter in procedure [duplicate]

This question already has answers here:
Passing an array of parameters to a stored procedure
(11 answers)
Closed 8 years ago.
sp_panelistid1 '585','201401','108972',''4','5''
alter procedure sp_panelistid1
(
#branch int,
#yearweak int,
#id int ,
#branchid varchar(10))
as
print #branchid
select f.lydelse as QuestionText, f.id as QuestionID, i.artal as Year, i.vecka as Week, i.id as Intervjuperson,
b.beskrivning as Branch, b.id as BranchID, v.beskrivning as Brand, v.id as BrandID, s.regperson as Buss, f.land as CountryID
, vi.NepaVikt as Weight , cp.CintPanelistId
from fraga f
inner join svar s on s.fraga = f.id
inner join bransch b on b.id = f.bransch
inner join varumarke v on v.id = s.varumarke
inner join intervjuperson i on i.id = s.intervjuperson
inner join vikt vi ON f.Bransch = vi.Bransch AND s.Intervjuperson = vi.Intervjuperson
inner join CintPanelistIntervjuperson cp on s.Intervjuperson=cp.Intervjuperson
where f.bransch = #branch
and (100*i.artal)+i.vecka > #yearweak
and f.land = 1 and f.id=#id
and v.beskrivning in (#branchid)
I need to pass multiple values in #branch id how do I pass parameters such that it works in 'IN condition ' like v.beskrivning in ('4','5','6','7 = Stämmer helt')
If you pass comma separated ids like this - '1, 2, 3' and if you want to use with "In" clause then you have to use Split() function. like this -
SELECT f.lydelse AS QuestionText
,f.id AS QuestionID
,i.artal AS Year
,i.vecka AS Week
,i.id AS Intervjuperson
,b.beskrivning AS Branch
,b.id AS BranchID
,v.beskrivning AS Brand
,v.id AS BrandID
,s.regperson AS Buss
,f.land AS CountryID
,vi.NepaVikt AS Weight
,cp.CintPanelistId
FROM fraga f
INNER JOIN svar s ON s.fraga = f.id
INNER JOIN bransch b ON b.id = f.bransch
INNER JOIN varumarke v ON v.id = s.varumarke
INNER JOIN intervjuperson i ON i.id = s.intervjuperson
INNER JOIN vikt vi ON f.Bransch = vi.Bransch
AND s.Intervjuperson = vi.Intervjuperson
INNER JOIN CintPanelistIntervjuperson cp ON s.Intervjuperson = cp.Intervjuperson
WHERE f.bransch = #branch
AND (100 * i.artal) + i.vecka > #yearweak
AND f.land = 1
AND f.id = #id
AND v.beskrivning IN (SELECT items FROM dbo.split(#branchid, ','))
Note: Split function is not in-built function. Its used defined table-valued function.
and here is the split function.
and here is the function.
CREATE FUNCTION [dbo].[Split] (
#String NVARCHAR(4000)
,#Delimiter CHAR(1)
)
RETURNS #Results TABLE (Items NVARCHAR(4000))
AS
BEGIN
DECLARE #INDEX INT
DECLARE #SLICE NVARCHAR(4000)
-- HAVE TO SET TO 1 SO IT DOESNT EQUAL Z
SELECT #INDEX = 1
IF #String IS NULL
RETURN
WHILE #INDEX != 0
BEGIN
-- GET THE INDEX OF THE FIRST OCCURENCE OF THE SPLIT CHARACTER
SELECT #INDEX = CHARINDEX(#Delimiter, #STRING)
-- NOW PUSH EVERYTHING TO THE LEFT OF IT INTO THE SLICE VARIABLE
IF #INDEX != 0
SELECT #SLICE = LEFT(#STRING, #INDEX - 1)
ELSE
SELECT #SLICE = #STRING
-- PUT THE ITEM INTO THE RESULTS SET
INSERT INTO #Results (Items)
VALUES (#SLICE)
-- CHOP THE ITEM REMOVED OFF THE MAIN STRING
SELECT #STRING = RIGHT(#STRING, LEN(#STRING) - #INDEX)
-- BREAK OUT IF WE ARE DONE
IF LEN(#STRING) = 0
BREAK
END
RETURN
END

optimize queries with a NOT IN (select...)

-- tf_wfget_appvr_records
create function [dbo].[tf_wfget_appvr_records] ( #cls_id int, #start_date datetime, #end_date datetime, #approver_id int, #co_id varchar( 5))
returns #wfapp_approver_status
table
( app_recgid bigint,
app_status varchar(1),
app_status_desc varchar( 80)
)
as
begin
insert into #wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select a.recgid, a.status, p.action
from cm_wfapp a
inner join cm_process p on a.proc_id = p.recgid
where a.co_id = #co_id and a.cls_id = #cls_id
and a.apply_date between #start_date and #end_date
and a.approver_id = #approver_id
-- insert others from cm_wftrn
insert into #wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select distinct a.recgid, a.status, p.action
from cm_wftrn c
inner join cm_process p on c.proc_id = p.recgid and p.action is not null
inner join cm_wfapp a on a.recgid = c.wfapp_id
where a.co_id = #co_id and a.cls_id = #cls_id
and a.apply_date between #start_date and #end_date
and c.wfapp_id not in ( select app_recgid from #wfapp_approver_status )
and c.appr_id = #approver_id
return
end
GO
It contain NOT IN constraint which is taking lot of time to extract result from database.
The Database is huge obviously.
How can I optimize this query?
Is there a way to optimize queries with a NOT IN (select...) ?
Please help thanks.
Replace your NOT IN with NOT EXISTS Operator something like this....
insert into #wfapp_approver_status
( app_recgid, app_status, app_status_desc)
select distinct a.recgid, a.status, p.action
from cm_wftrn c
inner join cm_process p on c.proc_id = p.recgid and p.action is not null
inner join cm_wfapp a on a.recgid = c.wfapp_id
where a.co_id = #co_id and a.cls_id = #cls_id
and a.apply_date between #start_date and #end_date
and c.appr_id = #approver_id
and not exists ( select 1
from #wfapp_approver_status
WHERE c.wfapp_id = app_recgid)