SSRS- multi value report data does not display in tablix - sql-server

below is my stored proc.
ALTER PROCEDURE [dbo].[Rpt_ProgramActivityReport ]
(
#StartDate DATETIME ,
#EndDate DATETIME ,
#RegionId varchar(25) = NULL,
#OrganizationId varchar(25) = NULL ,
#County varchar(25) = NULL,
#ActivityId varchar(25) = NULL,
#InterventionId varchar(25) = NULL,
#Status varchar(25) = NULL,
#StrategyId varchar(25) = NULL,
#MethodApproachId varchar(25) = NULL,
#TargetPopulationId varchar(25) = NULL,
#PrimaryProblemId varchar(25) = NULL,
#SecondaryProblemId varchar(25) = NULL,
#InterveningVariableId varchar(25) = NULL,
#FundingSourceId varchar(25)= NULL
)
AS
BEGIN
SELECT
FACT.Id fActivityId, FACT.ActivityName,
ACT.fOrganizationRegion_Id ,ACT.Id AS ActivityId,ACT.CreateUserId,
(US.LastName + ',' +US.FirstName)AS UserName,
REG.Id AS RegionId,REG.OrganizationName AS RegionName,
ORG.Id AS OrganizationId , ORG.OrganizationName AS OrganizationName,
FC.Id AS FundingSourceId, fc.FundingSource,
CA.Id AS CoverageAreaId, CA.County , CA.ZipCode
FROM Activities ACT
JOIN fActivity FACT ON FACT.Id = ACT.fActivity_Id
JOIN fOrganizationRegion ORGREG ON ORGREG.Id = ACT.fOrganizationRegion_Id
JOIN fOrganization REG ON REG.Id = ORGREG.RegionOrg_Id
JOIN fOrganization ORG ON ORG.Id = ORGREG.Org_Id
JOIN ActivityFundingSource AFC ON AFC.Activity_Id = ACT.Id
JOIN fFundingSource FC ON FC.Id = AFC.FundingSource_Id
JOIN ActivityCoverageArea ACA ON ACA.Activity_Id = ACT.Id
JOIN fCoverageAreas CA ON CA.Id = ACA.CoverageArea_Id
JOIN Users US ON US.UserId = ACT.CreateUserId
LEFT JOIN fInterventionType ITYPE ON ITYPE.Id = FACT.InterventionType_Id
LEFT JOIN ActivityInterveningVariable AIVAR ON AIVAR.Activity_Id = ACT.Id
LEFT JOIN fInterveningVariables IVAR ON IVAR.Id = AIVAR.fInterveningVariable_Id
LEFT JOIN ActivitySecondaryPriorityProblem ASPP ON ASPP.Activity_Id = ACT.Id
LEFT JOIN fPriorityProblem PP ON PP.Id = ASPP.fPriorityProblem_Id
LEFT JOIN fMethodApproach MA ON MA.Id = ACT.fMethodApproach_Id
LEFT JOIN fStrategyMethodApproach SMA ON SMA.fMethodApproach_Id = MA.Id
LEFT JOIN fStrategy ST ON ST.Id = SMA.fStrategy_Id
LEFT JOIN ActivityTargetPopulation ATP ON ATP.Activity_Id = ACT.Id
LEFT JOIN fTargetPopulation TP ON TP.Id = ATP.TargetPopulation_Id
WHERE
(Act.CreateDate BETWEEN #StartDate AND #EndDate)
AND ( (#RegionId IS NULL) OR REG.Id IN( SELECT * FROM dbo.FnSplit(#RegionId ,',' )) )
AND ((#OrganizationId IS NULL) OR ORG.Id IN ( SELECT * FROM dbo.FnSplit( #OrganizationId ,',' )))
AND ( (#County IS NULL) OR CA.County IN ( SELECT * FROM dbo.FnSplit( #County,',' ) ))
AND ((#ActivityId IS NULL) OR FACT.Id IN ( SELECT * FROM dbo.FnSplit( #ActivityId ,',' ) ) )
AND ( (#FundingSourceId IS NULL) OR FC.Id IN ( SELECT * FROM dbo.FnSplit(#FundingSourceId ,',' )) )
--AND ((#Status IS NULL) OR ACT.Completed IN (SELECT * FROM dbo.FnSplit( #Status ,',' )))
AND ((#Status IS NULL) OR ACT.Completed IN (SELECT * FROM dbo.FnSplit( cast(#Status as varchar) ,',' )))
AND ((#InterventionId IS NULL) OR ITYPE.Id IN ( SELECT * FROM dbo.FnSplit( #InterventionId ,',' ) ))
AND ((#InterveningVariableId IS NULL) OR IVAR.Id IN (SELECT * FROM dbo.FnSplit( #InterveningVariableId ,',' ) ))
AND ((#SecondaryProblemId IS NULL) OR PP.Id IN (SELECT * FROM dbo.FnSplit(#SecondaryProblemId ,',' )))
AND ((#PrimaryProblemId IS NULL) OR PP.Id IN (SELECT * FROM dbo.FnSplit( #PrimaryProblemId ,',' )))
AND ((#MethodApproachId IS NULL) OR MA.Id IN ( SELECT * FROM dbo.FnSplit(#MethodApproachId ,',' ) ))
AND ((#StrategyId IS NULL) OR ST.Id IN ( SELECT * FROM dbo.FnSplit(#StrategyId ,',' )))
AND ( (#TargetPopulationId IS NULL) OR TP.Id IN (SELECT * FROM dbo.FnSplit(#TargetPopulationId,',' )))
END
when I run it i see data.
also I have a report where I use the same stored proc in data set.
while I execute the data set I get the records.
but when I add the fields to the report tablix. it returns NO Records.
I Have also modified and checked the data with using the below codes in parameters in data set.
=Join(Parameters!RegionId.Value,",")
=Join(Parameters!OrganizationId.Value ,",")
=Join(Parameters!County.Value,",")
=Join(Parameters!ActivityId.Value,",")
=Join(Parameters!InterventionId.Value,",")
=Join(Parameters!Status.Value,",")
=Join(Parameters!StrategyId.Value,",")
=Join(Parameters!MethodApproachId.Value,",")
= Join(Parameters!TargetPopulationId.Value,",")
= Join(Parameters!PrimaryProblemId.Value,",")
= Join(Parameters!SecondaryProblemId.Value,",")
= Join(Parameters!InterveningVariableId.Value,",")
= Join(Parameters!FundingSourceId.Value,",")
but issue is I still get the records when i execute the data set separately . but in report tablix it does not display the data.
Can any one help me on this.??

Related

Optimize query with multiple calls to the same table

We are creating a view as follows:
create view [dca].[CodeDescriptions_VW]
as
select distinct
ek.EmpKey
, RTRIM(CONVERT(varchar(60), abt.fdesc)) AS AboriginalTypeDescription
, RTRIM(CONVERT(varchar(60), cma.fdesc)) AS CensusMetroAreaDescription
, RTRIM(CONVERT(varchar(60), q.c_desc)) AS CobraCodeDescription
, RTRIM(CONVERT(varchar(60), ct.fdesc)) AS ConsentTypeDescription
, RTRIM(CONVERT(varchar(60), li.fdesc)) AS DirectOrIndirectDescription
, RTRIM(CONVERT(varchar(60), dt.fdesc)) AS DisabilityTypeDescription
, RTRIM(CONVERT(varchar(60), doca.fdesc)) AS DocumentADescription
FROM
dbo.hrpersnl AS h
INNER JOIN
HRActions.dbo.EmployeeKey AS ek ON RTRIM(LTRIM(UPPER(h.p_empno))) = UPPER(ek.EmpNo) COLLATE SQL_Latin1_General_CP1_CI_AS
AND h.p_company = ek.Company COLLATE SQL_Latin1_General_CP1_CI_AS
LEFT OUTER JOIN
dbo.hrtables AS abt ON abt.ftable = ''AL'' AND RTRIM(h.p_abotype) = RTRIM(abt.code)
LEFT OUTER JOIN
dbo.hrtables AS cma ON cma.ftable = ''CM'' AND RTRIM(h.p_cma) = RTRIM(cma.code)
LEFT OUTER JOIN
dbo.hrtables AS ct ON ct.ftable = ''CS'' AND RTRIM(h.p_constype) = RTRIM(ct.code)
LEFT OUTER JOIN
dbo.hrtables AS li ON li.ftable = ''IN'' AND RTRIM(h.p_laborind) = RTRIM(li.code)
LEFT OUTER JOIN
dbo.hrtables AS dt ON dt.ftable = ''DI'' AND RTRIM(h.p_distype) = RTRIM(dt.code)
LEFT OUTER JOIN
dbo.hrtables AS doca ON doca.ftable = ''I2'' AND RTRIM(h.p_doca) = RTRIM(doca.code)
I am wondering if there is a more efficient way to reference the same table (dbo.hratables) multiple times. As is, this is a very costly view (there are actually about 3 dozen different 'Descriptions' that we need to query, I have only shown a few).
While not ideal, perhaps you could create an in-line TVF and use that vs all the joins.
Something like:
CREATE FUNCTION dbo.HRDescription (
#ftable VARCHAR(2), #code VARCHAR(50), #field VARCHAR(50)
)
RETURNS TABLE
AS
RETURN
(
SELECT RTRIM( CONVERT( VARCHAR(60),
CASE
WHEN #field = 'c_desc' THEN c_desc
ELSE fdesc
END ) ) AS [Value]
FROM dbo.hrtables
WHERE
ftable = #ftable AND RTRIM( code ) = #code
)
GO
And then modify your query:
SELECT DISTINCT
ek.EmpKey
, ( SELECT [Value] FROM dbo.HRDescription( 'AL', h.p_abotype, 'fdesc' ) ) AS AboriginalTypeDescription
, ( SELECT [Value] FROM dbo.HRDescription( 'CM', h.p_cma, 'fdesc' ) ) AS CensusMetroAreaDescription
, ( SELECT [Value] FROM dbo.HRDescription( 'CS', h.p_constype, 'fdesc' ) ) AS ConsentTypeDescription
, ( SELECT [Value] FROM dbo.HRDescription( 'IN', h.p_laborind, 'fdesc' ) ) AS DirectOrIndirectDescription
, ( SELECT [Value] FROM dbo.HRDescription( 'DI', h.p_distype, 'fdesc' ) ) AS DisabilityTypeDescription
, ( SELECT [Value] FROM dbo.HRDescription( 'I2', h.p_doca, 'fdesc' ) ) AS DocumentADescription
FROM dbo.hrpersnl AS h
INNER JOIN HRActions.dbo.EmployeeKey AS ek
ON RTRIM(LTRIM(UPPER(h.p_empno))) = UPPER(ek.EmpNo) COLLATE SQL_Latin1_General_CP1_CI_AS
AND h.p_company = ek.Company COLLATE SQL_Latin1_General_CP1_CI_AS;
Again, not ideal, but it may save on performance over the joins.

Simplify SQL where exists in clause

I want to simplify the below given procedure especially I want to remove most of the where clause filters such as IN and exists clauses.
For that, I have used a CTE and also declare a temp table and used it to get the select query that was talking long time since it was in where in clause. I would appreciate if you could show me some tricks in order to simplify this query.
ALTER PROCEDURE dbo.GetMappingBranchScenarios
#Mapping INT
#UserId INT= NULL
#BranchId INT = NULL
SELECT
BS.BranchId,
NULLIF( CC.Code, '' ) AS Code,
BS.BranchName,
BS.Active
FROM
Branch BS
LEFT OUTER JOIN
Code CC ON CC.BranchId = BS.BranchId
LEFT OUTER JOIN
BranchRule BRE ON BRE.MappingId = #Mapping
AND BRE.BranchId = BS.BranchId
WHERE
(BS.Active = 1
OR EXISTS (SELECT * FROM BranchRule BRE
WHERE BRE.BranchId = BS.BranchId
AND BRE.BranchId > 0
AND BRE.MappingId = #MappingId))
AND (#UserId IS NULL
OR BS.BranchId IN (SELECT BranchId
FROM branch2mapping.dbo.ListBranch(#UserId))
OR EXISTS (SELECT 1 FROM dbo.SecondaryMapping
WHERE Id = #UserId AND Admin = 1))
AND BS.BranchId = (CASE WHEN BranchId is NULL THEN BS.BranchID ELSE #BranchId END)
AND CC.Code = (CASE WHEN #Code IS NULL THEN CC.Code ELSE #Code END)
ORDER BY
CC.Code ASC
What I have done so far :
IF OBJECT_ID('tempdb..#Temp', 'U') IS NOT NULL
DROP TABLE #Temp
CREATE TABLE #Temp (BranchId INT)
SELECT BranchId
FROM branch2mapping.dbo.ListBranch(#UserId)
;WITH CTE AS
(
SELECT
BS.BranchId,
NULLIF(CC.Code, '' ) AS Code,
BS.BranchName, BS.Active
FROM
Branch BS
LEFT OUTER JOIN
Code CC ON CC.BranchId = BS.BranchId
LEFT OUTER JOIN
BranchRule BRE ON BRE.MappingId = #Mapping
AND BRE.BranchId = BS.BranchId
)
SELECT *
FROM CTE
WHERE
(CTE.Active = 1
OR EXISTS (SELECT * FROM BranchRule BRE
WHERE BRE.BranchId = CTE.BranchId
AND BRE.BranchId > 0
AND BRE.MappingId = #MappingId))
AND (#UserId IS NULL
OR BS.BranchId IN (SELECT * FROM #Temp)
OR EXISTS (SELECT 1 FROM dbo.SecondaryMapping
WHERE Id = #UserId AND Admin = 1)
)
AND BS.BranchId = (CASE WHEN BranchId is NULL THEN CTE.BranchID ELSE #BranchId END)
AND CTE.Code = (CASE WHEN #Code IS NULL THEN CTE.Code ELSE #Code END)
ORDER BY
CTE.Code ASC
Thank you for all your help.
Could you try if this is faster and still returning the same values with different filtering criteria?
ALTER PROCEDURE dbo.GetMappingBranchScenarios
#Mapping INT
#UserId INT= NULL
#BranchId INT = NULL
DECLARE #IsRuleExists BIT;
DECLARE #IsUrerADmin BIT;
IF EXISTS
(
SELECT 1
FROM Branch BS
INNER JOIN BranchRule BRE
ON BRE.BranchId = BS.BranchId
AND BRE.BranchId > 0
AND BRE.MappingId = #MappingId
)
BEGIN;
SET #IsRuleExists = 1;
END;
IF EXISTS
(
SELECT 1
FROM dbo.SecondaryMapping
WHERE Id = #UserId AND Admin = 1
) OR #UserId IS NULL
BEGIN;
SET #IsUrerADmin = 1;
END;
CREATE TABLE #Branches
(
[BranchId] INT
);
INSERT INTO #Branches ([BranchId])
SELECT BranchId
FROM branch2mapping.dbo.ListBranch(#UserId);
SELECT
BS.BranchId,
NULLIF( CC.Code, '' ) AS Code,
BS.BranchName,
BS.Active
FROM Branch BS
LEFT OUTER JOIN Code CC
ON CC.BranchId = BS.BranchId
WHERE
(
BS.Active = 1 OR #IsRuleExists = 1
)
AND
(
#IsUrerADmin = 1
OR
BS.BranchId IN (SELECT BranchId FROM #Branches)
)
AND BS.BranchId = (CASE WHEN BranchId is NULL THEN BS.BranchID ELSE #BranchId END)
AND CC.Code = (CASE WHEN #Code IS NULL THEN CC.Code ELSE #Code END)
ORDER BY CC.Code ASC;

SqlCommand.ExecuteReader became very slow

I am using this code, to call an SQL function, which returns entries from an SQL Server database table
string cmd = String.Format("select * from dbo.GetData(#userId, #fileId, #created);");
using (SqlConnection conn = new SqlConnection(connectionString))
{
if (conn.State != ConnectionState.Open)
conn.Open();
SqlCommand command = new SqlCommand(cmd, conn);
if (String.IsNullOrEmpty(userId))
command.Parameters.AddWithValue("#userId", DBNull.Value);
else
command.Parameters.AddWithValue("#userId", userId);
if (String.IsNullOrEmpty(fileId))
command.Parameters.AddWithValue("#fileId", DBNull.Value);
else
command.Parameters.AddWithValue("#fileId", docId);
command.Parameters.AddWithValue("#created", created);
internalWatch.Reset();
internalWatch.Start();
IDataReader reader = command.ExecuteReader();
table = GetDataTableFromDataReader(reader);
reader.Close();
reader.Dispose();
conn.Close();
internalWatch.Stop();
The table I am working with contains a bit more than 1.5 million entries and should return a bit more than 250k entries.
If I am executing the SQL function within SSMS it needs 8 seconds to return the results and I already used the code above last week to get the results within my desktop application. At this time everything was fine. The code needed between 10-12 seconds to get the results.
The strange thing is, that today the code needs more than 40 seconds to return the same results, but I haven't change anything within the SQL function or the code itself. The only change I did in my programm is adding a few more classes, which have nothing to do with the code above.
If I am debugging the code, I can see, that the line
IDataReader reader = command.ExecuteReader();
needs the most of the time now.
Since I haven't change anything in the SQL function or the code itself, I can't understand why it is taking so long now...
And if needed, here is the SQL function, I am using:
ALTER FUNCTION [dbo].[GetData]
(#userId varchar(128) = NULL,
#fileId varchar(192) = NULL,
#created DateTimeOffset(7))
RETURNS TABLE
AS
RETURN (
WITH FindNewestVersion AS
(
SELECT
*,
ROW_NUMBER() OVER (PARTITINO BY FileId, UserId
ORDER BY created DESC) rn
FROM
table1
)
SELECT
q.Created, q.Updated, q.FileId, q.UserId,
F.column1, F.column2, F.column3
FROM
table2 AS F
INNER JOIN
table1 AS q ON F.column4 = q.PersonId AND F.created = q.created
INNER JOIN
(SELECT
created, PersonId, DocumentId
FROM
FindNewestVersion
WHERE
rn = 1) AS x ON q.created = x.created
AND q.PersonId = x.PersonId
AND q.FileId = x.FileId
WHERE
(F.column1 = 'Sample')
AND (q.Created <= #created)
AND (q.Updated >= #created)
AND Q.PersonId = ISNULL(#userId, Q.PersonId)
AND Q.FileId = ISNULL(#fileId, Q.FileId)
)
Thank you for any suggestions!
This seems like a case of parameter sniffing
One thing that you could do is rewrite your procedure as follows:
`
DROP FUNCTION [dbo].[GetData]
CREATE PROCEDURE[dbo].[GetData]
(
#userId varchar(128) = NULL,
#fileId varchar(192) = NULL,
#created DateTimeOffset(7)
)
RETURNS TABLE
AS
DECLARE #l_userId varchar(128) = NULL,
DECLARE #l_fileId varchar(192) = NULL,
DECLARE #l_created DateTimeOffset(7)
SET #l_userId = userId
SET #l_fileId = fileId
SET #l_created = #created
(
WITH FindNewestVersion as
(
Select *, ROW_NUMBER()
over (partition by FileId, UserId ORDER BY created DESC)rn from table1
)
SELECT q.Created, q.Updated, q.FileId, q.UserId,
F.column1, F.column2, F.column3
FROM table2 AS F INNER JOIN
table1 AS q
ON F.column4 = q.PersonId AND F.created = q.created
INNER JOIN
(
select created, PersonId, DocumentId from FindNewestVersion where rn = 1
) AS x ON q.created = x.created AND q.PersonId = x.PersonId AND q.FileId = x.FileId
WHERE (F.column1 = 'Sample') AND (q.Created <= #created) AND (q.Updated >= #created)
And Q.PersonId = ISNULL(#l_userId, Q.PersonId)
And Q.FileId = ISNULL(#l_fileId, Q.FileId)
)
`
You can then get you data as you would by calling a stored procedure.
This seems like a case of SET ARITHABORT ON
By default in SQL it's On But while we execute Through C# Code then its not understand the ARITHABORT ON.
One thing that you could do is rewrite your procedure as follows:
DROP FUNCTION [dbo].[GetData]
CREATE PROCEDURE[dbo].[GetData]
(
#userId varchar(128) = NULL,
#fileId varchar(192) = NULL,
#created DateTimeOffset(7)
)
RETURNS TABLE
AS
SET ARITHABORT ON
DECLARE #l_userId varchar(128) = NULL,
DECLARE #l_fileId varchar(192) = NULL,
DECLARE #l_created DateTimeOffset(7)
SET #l_userId = userId
SET #l_fileId = fileId
SET #l_created = #created
(
WITH FindNewestVersion as
(
Select *, ROW_NUMBER()
over (partition by FileId, UserId ORDER BY created DESC)rn from table1
)
SELECT q.Created, q.Updated, q.FileId, q.UserId,
F.column1, F.column2, F.column3
FROM table2 AS F INNER JOIN
table1 AS q
ON F.column4 = q.PersonId AND F.created = q.created
INNER JOIN
(
select created, PersonId, DocumentId from FindNewestVersion where rn = 1
) AS x ON q.created = x.created AND q.PersonId = x.PersonId AND q.FileId = x.FileId
WHERE (F.column1 = 'Sample') AND (q.Created <= #created) AND (q.Updated >= #created)
And Q.PersonId = ISNULL(#l_userId, Q.PersonId)
And Q.FileId = ISNULL(#l_fileId, Q.FileId)
)`enter code here`

Select multiple columns but group by only one

Using SQL Server 2008. I have been researching this problem for days. Thought about CTE and trying to use a predicate on the problem tables.
Nothing I have tried or researched has worked so here I am. The problem is it's returning duplicate OrderID.
I've marked the problem joins.
Even tried OUTER APPLY but it caused certain searches not to work. Tried INNER APPLY then duplicates again.
The problem joins, the tables, have multiple references to OrderID.
So tblRun has multiple rows with the same OrderID showing which run it was in at and what date and so forth.
I really need suggestions from all the guru's out there.
Here is the SQL:
DECLARE #CompanyID INT = 22718,
#StartDate DATETIME = '',
#EndDate DATETIME = '',
#SalesRepID INT = NULL,
#AssignedTo INT = NULL,
#ServiceDefID INT = NULL,
#ProductName VARCHAR(512) = NULL,
#IsCCOrder BIT = NULL,
#OrderID INT = NULL,
#LocationID INT = NULL,
#SalesRepLocationID INT = NULL,
#PONum VARCHAR(150) = NULL,
#InvoiceID INT = NULL,
#IsSplitOrder BIT = NULL,
#ContactID INT = NULL,
#ContactName VARCHAR(150) = NULL,
#JobName VARCHAR(200) = NULL,
#Notes VARCHAR(MAX) = NULL,
#CompanyName VARCHAR(255) = NULL,
#DueDateFrom DATETIME = '',
#DueDateTo DATETIME = '',
#SubmitedDateFrom DATETIME = '',
#SubmitedDateTo DATETIME = '',
#IsRush BIT = NULL,
#Msg VARCHAR(1000) = NULL
--#Stages dbo.int_tbltype READONLY
DECLARE #Stages TABLE (ID INT)
--INSERT INTO #Stages (ID) VALUES (1)
DECLARE #DueDate DATETIME = NULL
SET NOCOUNT ON
DECLARE #OrderIDsTBL TABLE(OrderID INT)
IF #Msg IS NOT NULL
BEGIN
INSERT INTO #OrderIDsTBL (OrderID)
SELECT OrderID
FROM tblOrderLog
WHERE Msg LIKE '%' + #Msg + '%'
END
IF #OrderID IS NOT NULL
BEGIN
INSERT INTO #OrderIDsTBL (OrderID)
VALUES (#OrderID)
END
DECLARE #OderIDsCnt INT = (SELECT COUNT(OrderID) FROM #OrderIDsTBL)
DECLARE #StageCnt INT = (SELECT COUNT(ID) FROM #Stages)
SELECT
o.OrderID,
o.CompanyID,
co.Name AS CompanyName,
o.ContactID,
o.JobName,
p.FirstName + ' ' + p.LastName AS ContactName,
p2.FirstName + ' ' + p2.LastName AS SalesRep,
o.DueDate,
CASE WHEN MAX(oi.PriorityService) > 0 THEN 1 ELSE 0 END AS IsRush,
ISNULL(s.StageID, 0) AS StageID,
o.Notes, r.SubmittedComplete,
dbo.fOrderRunLocationCSVByOrderID(o.OrderID) AS LocationCSV,
(SELECT
STUFF((SELECT DISTINCT ' ' + st.Name + '<br />' FROM tblStage st
INNER JOIN tblOrderItem oi ON oi.OrderID = o.OrderID
INNER JOIN tblRun r ON r.OrderItemID = oi.OrderItemID
INNER JOIN tblStage s ON s.StageID = r.StageID
LEFT JOIN tblRunService rs ON rs.RunID = r.RunID
WHERE (s.StageID = st.StageID)
AND (rs.AssignedTo = #AssignedTo OR #AssignedTo IS NULL)
FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, ''))
AS Stages,
Row_Number() Over(Order By o.OrderID Desc) As RowNum
FROM
tblOrder o
INNER JOIN
tblCompany co ON co.CompanyID = o.CompanyID
INNER JOIN
tblParty p ON p.PartyID = o.ContactID
-------- PROBLEM JOINS ------------
LEFT JOIN
tblOrderItem oi ON oi.OrderID = o.OrderID
LEFT JOIN
tblRun r ON r.OrderItemID = oi.OrderItemID
LEFT JOIN
tblService srv ON srv.OrderItemID = oi.OrderItemID
-------- END PROBLEM JOINS ------------
LEFT JOIN
tblStage s ON s.StageID = r.StageID
LEFT JOIN
tblParty p2 ON p2.PartyID = o.SalesRepID
LEFT JOIN
tblEmployee e ON e.EmployeeID = o.SalesRepID
LEFT JOIN
tblShipTo st ON o.ShipToID = st.ShipToID
WHERE
(#CompanyID IS NULL OR (o.CompanyID = #CompanyID )) AND
(#IsCCOrder IS NULL OR (ISNULL(o.IsCreditCardOrder, 0) = #IsCCOrder )) AND
(#SalesRepID IS NULL OR o.SalesRepID = #SalesRepID) AND
(#ServiceDefID IS NULL OR (srv.ServiceDefID = #ServiceDefID)) AND
(#ProductName IS NULL OR (oi.Name LIKE '%' + #ProductName + '%')) AND
(#IsSplitOrder IS NULL OR (#IsSplitOrder = 1 AND oi.SplitOrderID IS NOT NULL)) AND
(
(#StartDate = '' OR #EndDate = '') OR
(#StartDate >= CreatedDate AND #EndDate <= COALESCE(CancelledDate, ClosedDate, GetDate())) OR
(#StartDate <= COALESCE(CancelledDate, ClosedDate, GETDATE()) AND #EndDate >= COALESCE(CancelledDate, ClosedDate, GetDate()) ) OR
(#StartDate <= CreatedDate AND #EndDate >= CreatedDate )
) AND
(#LocationID IS NULL OR (#LocationID = srv.LocationID OR srv.LocationID IS NULL)) AND
(#SalesRepLocationID IS NULL OR (#SalesRepLocationID = e.LocationID OR e.LocationID IS NULL))
AND (#InvoiceID IS NULL OR o.InvoiceID = #InvoiceID )
AND (#PONum IS NULL OR o.PONum LIKE '%' + #PONum + '%')
AND (COALESCE(s.StageID, 0) IN (SELECT ID FROM #Stages) OR #StageCnt = 0)
AND (o.ContactID = #ContactID OR #ContactID IS NULL)
AND (p.FirstName + ' ' + p.LastName LIKE '%' + #ContactName + '%' OR #ContactName IS NULL)
AND (o.JobName LIKE '%' + #JobName + '%' OR #JobName IS NULL)
AND (o.Notes LIKE '%' + #Notes + '%' OR #Notes IS NULL)
AND (co.Name LIKE '%' + #CompanyName + '%' OR #CompanyName IS NULL)
AND (o.DueDate >= #DueDateFrom OR #DueDateFrom = '')
AND (o.DueDate <= #DueDateTo OR #DueDateTo = '')
AND (r.SubmittedComplete >= #SubmitedDateFrom OR #SubmitedDateFrom = '')
AND (r.SubmittedComplete <= #SubmitedDateTo OR #SubmitedDateTo = '')
AND (#IsRush = (CASE WHEN oi.PriorityService > 0 THEN 1 ELSE 0 END)
OR #IsRush IS NULL)
AND (o.OrderID IN (SELECT OrderID FROM #OrderIDsTBL) OR #OderIDsCnt = 0)
GROUP BY
o.OrderID, o.CompanyID,
co.Name,
o.ContactID, o.JobName,
p.FirstName, p.LastName, p2.FirstName, p2.LastName,
o.DueDate, o.Notes,
r.SubmittedComplete,
s.StageID
Thanks for any suggestions. I've been working on this for some time now and just can't get it working right.
It looks like you're trying to do too much with a single SELECT statement. If you want one row per unique OrderID, then don't join with the tables that have multiple rows for the same OrderID. Remove the GROUP BY clause. Use one or more separate SELECT statements to get the details from the tables that have multiple rows per OrderID.
Thanks everyone for the suggestions but I found my own solution.
With the entire sql, I placed it into a temp table.
Then used this to sort out the duplicate OrderIds....
SELECT OrderID, CompanyID, ContactID, CompanyName, JobName, ContactName,
SalesRep, DueDate, IsRush , StageID, Notes, SubmittedComplete,
LocationCSV, Stages
FROM (SELECT *, ROW_NUMBER() OVER(PARTITION BY OrderID ORDER BY OrderID DESC) 'RowRank'
FROM #SearchTbl
)sub
WHERE RowRank = 1

Performance issue because of left join and multiple where clause

Here is the procedure
create PROCEDURE [dbo].[sample1] (
#param1 varchar(20) ,
#param2 VARCHAR(5),
#param3 varchar(max) = NULL,
#param4 varchar(max) = NULL,
#param5 varchar(max) = NULL,
#param6 bit = 1,
#param7 varchar(max) = NULL,
#param8 bit = 1,
#param9 varchar(max) = NULL,
#param10 varchar(max) = NULL,
#param11 varchar(max) = NULL,
#param12 varchar(5) = 'OP',
#param13 varchar(max) = NULL,
#TOP int = 101,
#SORTFIELD varchar(20) = 'DESCRIPTION',
#SORTDIRECTION varchar(5) = 'ASC'
)
AS
BEGIN
DECLARE
#NOW VARCHAR(10)=(SELECT CONVERT(varchar(10), GETDATE(), 112)),
#PHYSNAME VARCHAR(50)='',
#PHYPARAMS CHAR(1)='N'
/*********************************/
SELECT CPPACKAGE_PARAMS, MIN(CODE) AS MinCode, MAX(CODE) AS MaxCode
INTO #SNCPPKG_PARAMS_DTLS
FROM SNCPPKG_PARAMS_DTLS
WHERE CODETYPE = 5
GROUP BY CPPACKAGE_PARAMS
SELECT *
INTO #SNCPPACKAGERL
FROM SNCPPACKAGERL
WHERE DOMDEF = #param1
--SELECT *
--INTO #SNCPPROCDEF
--FROM SNCPPROCDEF
--WHERE DOMDEF = #param1
--SELECT *
--INTO #SNCPDIAGDEF
--FROM SNCPDIAGDEF
--WHERE DOMDEF = #param1
/*********************************/
SELECT
#PHYPARAMS=[ParamaterValue]
FROM [dbo].[sntbFacilityParamaters] with(nolock)
where [ParamaterTypeId] =
(SELECT TOP 1 [ParamaterTypeId]
FROM [dbo].[sntbParamaterTypeRef] with(nolock)
where ParamaterTypeName ='Physician Specific Packages')
and facid = #param2
IF( ISNULL(#PHYPARAMS ,'N')='N')
BEGIN
SET #param11=''
END
SET NOCOUNT ON;
CREATE TABLE #tempGLT1DET (CODEFROM VARCHAR(32))
INSERT INTO #tempGLT1DET
SELECT A.CODEFROM FROM snlocGLT1DET A with(nolock)
INNER JOIN snlocGLTABLE1 B with(nolock) ON A.GLTABLE1 = B.SYSKEY
WHERE A.CODETYPE IN ('4', '5')
AND NAME = 'AMA HCPCS'
AND (B.EFF_DATE <= #NOW OR B.EFF_DATE='')
AND (B.TRM_DATE >= #NOW OR B.TRM_DATE='')
AND (B.ACTIVATION_DT <= #NOW)
if(#top>300)
BEGIN
SET #top=300
END
IF(ISNULL(#param5,'')='' )
BEGIN
SET #param6=0
END
IF( ISNULL(#param7,'')='')
BEGIN
SET #param8=0
END
SELECT * INTO #TEMPPACKAGECOMPLETE
FROM
(SELECT --TOP(#TOP)
A.SYSKEY,
A.MCOMMORD,
A.SERVTYPE,
A.DESCRIPTION,
isnull(A.some_ver,'9') as some_ver,
A.ER,
A.OUTPATIENT,
A.INPATIENT,
A.DRG,
A.EFF_DATE,
A.TRM_DATE,
A.DOMDEF,
A.FINCLASS,
A.FORMORD,
A.AUDIT,
A.ALTDESC,
A.CODE,
B.TOTALCHARGE,
--null AS PHYSNAME,
A.PHYSNAME,
--NULL AS NPI,
A.NPI,
A.CPPACKAGE_PARAMS,A.PROCCODE,A.HCPCSRATES
--,row_number() over(partition BY A.SYSKEY
-- ORDER BY A.SYSKEY) rn
FROM
(SELECT *
FROM
(SELECT --TOP(#TOP)
CPPACKAGEDEF.SYSKEY,
isnull(CPPACKAGEDEF.some_ver,'9') as some_ver,
CPPACKAGEDEF.MCOMMORD,
CPPACKAGEDEF.SERVTYPE,
CPPACKAGEDEF.DESCRIPTION AS 'DESCRIPTION',
CPPACKAGEDEF.ER,
CPPACKAGEDEF.OUTPATIENT,
CPPACKAGEDEF.INPATIENT,
CPPACKAGEDEF.DRG,
CPPACKAGEDEF.EFF_DATE,
CPPACKAGEDEF.TRM_DATE,
CPPACKAGEDEF.DOMDEF,
CPPACKAGEDEF.FINCLASS,
CPPACKAGEDEF.FORMORD,
CPPACKAGEDEF.AUDIT,
CPPACKAGEDEF.ALTDESC,
REVDET.REVCODE, --REMOVE
P.PROCCODE,REVDET.HCPCSRATES,
CODE = CASE WHEN ISNULL(params.MinCode,'') = '' THEN ''
WHEN params.MinCode = params.MaxCode THEN params.MinCode
ELSE 'Multiple' END,
-- CODE = CASE WHEN
--(SELECT count(1)
-- FROM SNCPPKG_PARAMS_DTLS d with(nolock)
-- WHERE CPPACKAGE_PARAMS = CPPACKAGEDEF.CPPACKAGE_PARAMS
-- AND CODETYPE = 5) > 1 THEN 'Multiple' ELSE ISNULL(
-- (SELECT CODE
-- FROM SNCPPKG_PARAMS_DTLS d with(nolock)
-- WHERE CPPACKAGE_PARAMS = CPPACKAGEDEF.CPPACKAGE_PARAMS
-- AND CODETYPE = 5), '') END,
CPPACKAGEDEF.CPPACKAGE_PARAMS,
ISNULL(SC_TYPE,'R')AS SC_TYPE
FROM SNCPPACKAGEDEF AS CPPACKAGEDEF with(nolock)
LEFT JOIN #SNCPPKG_PARAMS_DTLS AS params ON params.CPPACKAGE_PARAMS = CPPACKAGEDEF.CPPACKAGE_PARAMS
LEFT JOIN #SNCPPACKAGERL REVDET ON REVDET.CPPACKAGEDEF= CPPACKAGEDEF.syskey-- and REVDET.domdef= #param1
--start:rajesh:for diag and proc
left join SNCPPROCDEF p with (nolock) on (P.CPPACKAGEDEF = CPPACKAGEDEF.syskey) and p.domdef= #param1
left join SNCPDIAGDEF d with (nolock) on (d.CPPACKAGEDEF = CPPACKAGEDEF.syskey) and d.domdef= #param1
--LEFT JOIN SNCPPACKAGERL pkgRL ON pkgRL.CPPACKAGEDEF= C.syskey
where
(
((isnull(#param5,'')='') or (d.DIAGCODE like #param5+'%'))
and
((isnull(#param7,'')='') or (p.PROCCODE like #param7+'%'))
)
AND
(
((#param13='9') AND (ISNULL(CPPACKAGEDEF.some_ver,'9')='9')) OR
((#param13='0') AND (ISNULL(CPPACKAGEDEF.some_ver,'9')='0'))
OR
(ISNULL(#param13,'')='')
)
--AND REVDET.
-- AND p.DOMDEF = #param1
--AND d.DOMDEF = #param1
AND
(
ISNULL(#param7,'')=''
OR
(
(#param12='IP' AND ISNULL(#param7,'')<>'')
--AND
--(
--( P.PROCCODE IN
-- ( SELECT DISTINCT DESTCODE FROM snVwCodeXWalk XWALK WHERE XWALK.SOURCECODE = #param10)
--)
--)
)
OR
(
((#param12='OP' OR #param12='ER') AND ISNULL(#param7,'')<>'')
AND
(
REVDET.HCPCSRATES like #param10+'%'
)
)
)
AND
(
(
( (#param5=1 AND #param8=0 )
AND
(d.SEQUENCE=1)
)
--or ISNULL(#param5,'')=''
)
OR
(
((#param8=1 AND #param6=0) AND
(p.SEQUENCE=1) )
--OR ISNULL(#param7,'')=''
)
OR
(
(
(#param5=1 )--AND ISNULL(#param5,'')<>'')
AND (#param8=1)-- AND ISNULL(#param7,'')<>'')
AND (p.SEQUENCE=1 )
AND (d.SEQUENCE=1 )
)
)
OR
(#param5=0 AND #param8=0)
)
--end:rajesh for diag and proc
--where SYSKEY = '126FAQ00249R' and
AND
(
(CPPACKAGEDEF.DESCRIPTION LIKE '%'+#param3+'%')
OR (CPPACKAGEDEF.ALTDESC LIKE '%'+#param3+'%')
OR (ISNULL(#param3,'')='')
)
AND
( (REVDET.REVCODE LIKE #param9+'%') OR (ISNULL(#param9,'')='' ))
AND( (CPPACKAGEDEF.DRG LIKE #param4+'%') OR (ISNULL(#param4,'')='') )
AND
-- ISNULL(CPPACKAGEDEF.SC_TYPE,'R')=
-- CASE WHEN #PHYPARAMS='Y'
-- THEN 'P'
--ELSE
--'R'
--end
(
(#PHYPARAMS='Y' AND CPPACKAGEDEF.SC_TYPE='P' AND ISNULL(#param11,'')<>'' )
OR
(#PHYPARAMS='Y'AND ISNULL(#param11,'')='' )
OR
(#PHYPARAMS='N'AND ISNULL(CPPACKAGEDEF.SC_TYPE,'R')='R' )
)
AND (CPPACKAGEDEF.EFF_DATE <= #NOW OR ISNULL(CPPACKAGEDEF.EFF_DATE,'')='')
AND (CPPACKAGEDEF.TRM_DATE >= #NOW OR ISNULL(CPPACKAGEDEF.TRM_DATE,'')='')
AND CPPACKAGEDEF.DOMDEF=#param1
--AND p.DOMDEF=#param1
--AND d.DOMDEF=#param1
) CPPACKAGEDEF
LEFT JOIN
(SELECT PHYSNAME,
phyPARAMS,
NPI
FROM
(SELECT DISTINCT b.PHYSNAME,
b.NPI,
cp.SYSKEY phyPARAMS,
ROW_NUMBER() OVER (PARTITION BY b.NPI,cp.SYSKEY
ORDER BY b.MDATE DESC) AS rowNum
FROM dbo.BILLPHYS b
INNER JOIN SNCPPACKAGE_PARAMS cp with(nolock) ON cp.NPI = b.NPI
WHERE ISNULL(b.NPI, '') <> '') phy
WHERE phy.rowNum=1) B ON B.phyPARAMS = CPPACKAGEDEF.CPPACKAGE_PARAMS
WHERE (CPPACKAGEDEF.SYSKEY <> ''
AND CPPACKAGEDEF.AUDIT = 'Z')
AND (CPPACKAGEDEF.DOMDEF IN (#param1))
AND (
((CPPACKAGEDEF.INPATIENT = 'Y') AND (#param12='IP'))
OR
((CPPACKAGEDEF.OUTPATIENT = 'Y') AND (ISNULL(#param12,'OP')='OP'))
OR
((#param12='ER' AND CPPACKAGEDEF.OUTPATIENT = 'Y' )AND CONVERT(INT,CPPACKAGEDEF.REVCODE) BETWEEN 450 AND 459)
)
) A
LEFT JOIN
(SELECT SUM(CONVERT(MONEY, LINECHARGE) * UNITS) AS 'TOTALCHARGE', CPPACKAGEDEF FROM
(SELECT LINECHARGE,
UNITS,
CPPACKAGEDEF
FROM #SNCPPACKAGERL with(nolock)) B
GROUP BY CPPACKAGEDEF) B ON A.SYSKEY = B.CPPACKAGEDEF
) A
-- LEFT JOIN SNCPPACKAGERL REVDET ON REVDET.CPPACKAGEDEF= A.syskey AND REVDET.DOMDEF=#param1
WHERE
--rn= 1
--AND
( (A.PHYSNAME LIKE #param11+'%') OR (ISNULL(#param11,'')='' ))
--
--select * from #TEMPPACKAGECOMPLETE
---
--SELECT count(DISTINCT SYSKEY)FROM #TEMPPACKAGE
-- gpant start
Select top (#top) * into #TEMPPACKAGE from (Select *,row_number() over(partition BY SYSKEY
ORDER BY SYSKEY) rn from #TEMPPACKAGECOMPLETE where ((
ISNULL(#param7,'')=''
OR
(
(#param12='IP' AND ISNULL(#param7,'')<>'')
AND
(
( PROCCODE IN
( SELECT DISTINCT DESTCODE FROM snVwCodeXWalk XWALK WHERE XWALK.SOURCECODE = #param10)
)
)
)
OR
(
((#param12='OP' OR #param12='ER') AND ISNULL(#param7,'')<>'')
--AND
--(
-- HCPCSRATES like #param10+'%'
--)
)
) ))t where rn =1
-- --gpant end
SELECT
--count(distinct T.SYSKEY) AS ScSyskey
T.SYSKEY AS ScSyskey,
T.DESCRIPTION AS ScDescription,
T.PHYSNAME AS ScPhysician ,
CASE WHEN ISNULL(#param12 ,'OP')='OP' THEN 'OP'
ELSE
CASE WHEN #param12='IP' THEN 'IP'
ELSE
CASE WHEN #param12='ER' THEN 'ER'
END
END
END ScPatientType,
--'I' AS ScPatientType,
T.DRG AS ScDiagnosis,
T.CODE AS ScPrimaryCdmProcedure ,
CASE WHEN P.DIAG_PRIMARYCODE='Y' THEN P.DIAGCODE ELSE NULL END AS ScPrimaryIcdDiagnosis,
CASE WHEN P.PROC_PRIMARYCODE='Y' THEN P.PROCCODE ELSE NULL END AS ScPrimaryIcdProcedure,
ISNULL(T.TOTALCHARGE, 0) AS ScAmount,
T.MCOMMORD AS ScClaimCount,
C.CODE AS ScCode,
C.CODETYPEDESC AS ScCodeType,
T.DESCRIPTION AS ScCodeDescription,
CAST(C.DATEFROM AS DATETIME) AS ScDateFrom,
CAST(C.DATETO AS DATETIME) As ScDateTo,
REVCODE.UNITS AS CdmUnits,
REVCODE.UNITSORDAYS AS CdmUnitType,
REVCODE.CPT4 AS CdmCode,
REVCODE.MODIFIERS AS CdmModifier,
REVCODE.REVCODE AS CdmRevenueCode,
REVCODE.REVDESC AS CdmDescription,
REVCODE.CHARGECODE AS CdmChargeCode,
REVCODE.LINECHARGE AS CdmPerUnitCharge,
P.DIAGCODE AS IcdDiagCode,
P.DIAG_PRIMARYCODE AS IcdDiagIsPrimary,
P.DIAGDESC AS IcdDiagDescription,
P.PROCCODE AS IcdProcCode,
P.PROC_PRIMARYCODE AS IcdProcIsPrimary,
P.PROCDESCS AS IcdProcDescription,
p.ProcedureSequence,
p.DiagSequence
FROM #TEMPPACKAGE T
LEFT JOIN
(
select distinct x.syskey as CPPACKAGEDEF,
proce.PROCCODE AS PROCCODE,
diag.DIAGCODE AS DIAGCODE,
PROCDESC.PROCDESC AS PROCDESCS ,
DIAGDESC.DIAGDESC AS DIAGDESC,
ISNULL(PROCDESC.ICD_CODE_VERSION,'ICD9Proc') as proccode_version ,
ISNULL(DIAGDESC.ICD_CODE_VERSION,'ICD9Dx') as diagcode_version, --ISNULL(p.DIAGDESC.ICD_CODE_VERSION,'ICD9Dx')
PROCDESC.VALID AS ISPROCVALID,
DIAGDESC.VALID AS ISDIAGVALID,
CASE WHEN PROCE.SEQUENCE =1 THEN 'Y' ELSE 'N' END AS PROC_PRIMARYCODE,
CASE WHEN DIAG.SEQUENCE =1 THEN 'Y' ELSE 'N' END AS DIAG_PRIMARYCODE ,
PROCE.SEQUENCE AS ProcedureSequence,
DIAG.SEQUENCE AS DiagSequence
from
--(
(
select distinct c.syskey as syskey
from snCPPACKAGEDEF C where domdef=#param1
)x
left join SNCPPROCDEF proce on (x.syskey=proce.CPPACKAGEDEF and proce.DOMDEF = #param1)
left join SNCPDIAGDEF diag on (x.syskey=diag.CPPACKAGEDEF and diag.DOMDEF = #param1)
left join SNLOCCP_DTPROC PROCDESC with(nolock) ON (proce.PROCCODE = PROCDESC.PROCCODE and PROCDESC.valid='Y' )
LEFT JOIN SNLOCCP_DTDIAG DIAGDESC with(nolock) ON (diag.DIAGCODE = DIAGDESC.DIAGCODE and DIAGDESC.valid='Y')
) P
ON T.SYSKEY = P.CPPACKAGEDEF
LEFT JOIN
VWCODEDESC AS C ON T.CPPACKAGE_PARAMS = C.CPPACKAGE_PARAMS
LEFT JOIN
(SELECT DISTINCT pkgRL.CPPACKAGEDEF, pkgRL.CHARGECODE, pkgRL.UNITS, pkgRL.UNITSORDAYS, pkgRL.SEQUENCE,
pkgRL.PERRELEVANCE, CAST(ISNULL(pkgRL.MOD1,'') + ','+ ISNULL(pkgRL.MOD2,'') + ','+ ISNULL(pkgRL.MOD3,'')+ ','+ ISNULL(pkgRL.MOD4,'') AS VARCHAR(50)) AS MODIFIERS, pkgRL.UNITWEIGHT,
ISNULL(pkgRL.REVDESC,'Procedure no longer exists!') AS REVDESC, pkgRL.HCPCSRATES,
pkgRL.REVCODE, pkgRL.LINECHARGE, pkgRL.STATCHARGE, pkgRL.CDMCHARGE,
CASE WHEN pkgRL.HCPCSRATES = '' OR pkgRL.HCPCSRATES IN (SELECT CODEFROM FROM #tempGLT1DET) THEN pkgRL.HCPCSRATES ELSE 'Invalid HCPCS Code:' + pkgRL.HCPCSRATES END AS 'CPT4'
FROM #SNCPPACKAGERL pkgRL ) revcode
ON T.SYSKEY = revcode.CPPACKAGEDEF
where
--(ISNULL(p.PROCCODE,'')<>'' OR ISNULL(p.DIAGCODE,'')<>'')
--AND
ISNULL(ISDIAGVALID,'Y')='Y' AND ISNULL(ISPROCVALID,'Y')='Y'
and
(
(
(
(T.some_ver='9' AND ISNULL(p.diagcode_version,'ICD9Dx')='ICD9Dx' )
OR
(T.some_ver='0' AND p.diagcode_version='ICD10CM')
OR
(ISNULL(P.DIAGCODE,'')='')
)
AND
(
(T.some_ver='9' AND ISNULL(p.proccode_version,'ICD9Proc')='ICD9Proc' )
OR
(T.some_ver='0' AND p.proccode_version='ICD10PCS')
OR
(ISNULL(P.PROCCODE,'')='')
)
)
OR
((ISNULL(P.DIAGCODE,'')='')OR(ISNULL(P.PROCCODE,'')='') )
)
ORDER BY CASE
WHEN UPPER(#SORTFIELD) = 'DESCRIPTION' AND
#SORTDIRECTION = 'DESC' THEN T.DESCRIPTION
END DESC,
CASE
WHEN UPPER(#SORTFIELD) = 'DESCRIPTION' AND
#SORTDIRECTION != 'DESC' THEN T.DESCRIPTION
END ASC,
CASE
WHEN UPPER(#SORTFIELD) = 'CHARGECODE' AND
#SORTDIRECTION = 'DESC' THEN
T.SYSKEY
END DESC,
CASE
WHEN UPPER(#SORTFIELD) = 'CHARGECODE' AND
#SORTDIRECTION != 'DESC' THEN
T.SYSKEY
END ASC
END
In the procedure param1 and param2 are mandatory. when I search with the rest of the params, my procedure is giving me average performance(withing 10-12 seconds). But When I search with param10 I am getting the result in 16 minutes which is unacceptable. I have tried to tweak the procedure by changing the where clause positions, implementing temp tables but did not help.
Suggest some ways which can increase the performance with only param10.
Try creating an index on REVDET.HCPCSRATES and then on snVwCodeXWalk.SOURCECODE. Try one first, then the other, then both, and see what effect it has.

Resources