Issue In Sql Stored Procedure - sql

In the below sql query When i execute it with some values in where condition it displays data and if i place values in [Sp_GrnValuationReportV1]--1,'GR140000001','GR140000009','2014-10-11','2014-12-25' it is display no data.Please help me to solve the issue.
ALTER PROCEDURE [dbo].[Sp_GrnValuationReportV1] --1,'GR140000001','GR140000009','2014-10-11','2014-12-25'
-- Add the parameters for the stored procedure here
#i_LocationID int,
#i_GrnStartNo varchar,
#i_GrnEndNo varchar,
#d_StartDate DATE,
#d_EndDate DATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT DISTINCT GRN.GoodsReceivedNoteNo,GRN.LocationID,GRN.CreatedOn,PO.PurchaseOrderNo,V.VendorName,
GRN.SupplierInvoiceNo,GRN.SupplierInvoiceDate,SR.LRNO,T.TransporterName,
CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.FreightCharges ), 0.00)
ELSE Isnull(( OEC.FreightCharges ), 0.00)
END FreightCharge,CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.LoadingCost + GRND.UnloadingCost ), 0.00)
ELSE Isnull(( OEC.LoadingCost + OEC.UnloadingCost ), 0.00)
END LoadingandUnloadingcharges ,
P.ProductCode,P.ProductName,GRND.ReceivedQuantity,GRND.RejectedQuantity,GRND.AcceptedQuantity,
GRND.UnitPrice AS BasicRate,ISNULL( (GRND.UnitPrice*GRND.ReceivedQuantity),0.00) BasicValue,GRND.VAT,CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.FreightCharges ), 0.00)
ELSE Isnull(( OEC.FreightCharges ), 0.00)
END FreightApportioned,
CASE
WHEN Count(GRND.GoodsReceivedNoteID) OVER(partition BY GRND.GoodsReceivedNoteID) > 1
THEN Isnull(( GRND.LoadingCost + GRND.UnloadingCost ), 0.00)
ELSE Isnull(( OEC.LoadingCost + OEC.UnloadingCost ), 0.00)
END LoadingandUnloadingApportioned,ISNULL((GRND.UnitPrice+OEC.FreightCharges+OEC.LoadingCost+OEC.UnloadingCost),0.00)AS TotalCost
FROM GoodsReceivedNoteDetail GRND
LEFT OUTER JOIN GoodsReceivedNote GRN ON GRN.GoodsReceivedNoteID=GRND.GoodsReceivedNoteID
LEFT OUTER JOIN PurchaseOrder PO ON PO.PurchaseOrderID=GRN.PurchaseOrderID
LEFT OUTER JOIN Vendor V ON V.VendorID=PO.VendorID
LEFT OUTER JOIN SecurityRegister SR ON SR.SecurityRegisterID=GRN.SecurityRegisterID
LEFT OUTER JOIN Transporter T ON T.TransporterID=SR.TransporterID
LEFT OUTER JOIN OtherExpenseCost OEC ON OEC.GoodsReceivedNoteID=GRN.GoodsReceivedNoteID
LEFT OUTER JOIN Product P ON P.ProductID=GRND.ProductID
--WHERE GRN.LocationID=#i_LocationID AND GRN.GoodsReceivedNoteNo>=#i_GrnStartNo AND GRN.GoodsReceivedNoteNo<=#i_GrnEndNo or GRN.CreatedOn>=#d_StartDate AND GRN.CreatedOn<=#d_EndDate
WHERE CAST( GRND.CreatedOn AS DATE)>=#d_StartDate AND GRN.LocationID=1 AND CAST( GRND.CreatedOn AS DATE) <=#d_EndDate AND GRN.GoodsReceivedNoteNo>= #i_GrnStartNo AND GRN.GoodsReceivedNoteNo <=#i_GrnEndNo

To find the problem in the big queries follow this instructions
Copy and Paste the body of stored proc to a new query window
change the columns in select to *. I mean change your query to select * from
declare the parameters at the top of query and set the values to them
Start commenting the joins and run the query to see which one makes it to return no rows. you might need to comment the corresponding conditions in where statement.
I hope this helps you

Mention The Size of varchar
#i_GrnStartNo varchar(50),
#i_GrnEndNo varchar(50),

Related

Order By Statement

I want to order the Time in ASC for the below query. I tried adding ORDER BY after WHERE clause but can't get the result as join statements are used. I have added the full sql query here.
ALTER PROCEDURE [dbo].[USP_GetFlightInfo]
(
#Origin NVARCHAR(50)=null,
#Destination NVARCHAR(50)=null,
#FlightNo NVARCHAR(50)= null
)
AS
BEGIN
SET NOCOUNT ON;
IF #FlightNo IS NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=#Origin and tfs.Destination =#Destination
ORDER BY tfs.[Time];
)
ELSE IF #FlightNo IS NOT NULL
(
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,tfSSS.DescriptionName, tfSS.FlightStatus from tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
where tfs.Origin=#Origin and tfs.Destination =#Destination and tfs.FlightNo=#FlightNo and tfs.FlightNo =#FlightNo
ORDER BY tfs.[Time];
)
END
Just put:
SELECT tfs.FlightNo,tfs.Origin,tfs.Destination,tfs.[Time],tfs.RevisedTime,
tfSSS.DescriptionName, tfSS.FlightStatus
FROM tblFlightSchedule tfs
INNER JOIN tblFlightStatus tfSS ON tfs.FSId= tfSS.FSId
LEFT OUTER JOIN tblFlightStatusDescription tfSSS ON tfSSS.FSDId= tfs.FSDId
WHERE tfs.Origin=#Origin and
tfs.Destination =#Destination and
(
tfs.FlightNo =#FlightNo or
#FlightNo is null
)
ORDER BY tfs.[Time];
As the code inside your stored procedure. No need for the IF and duplicating the query.
The main issue in your existing code is that SQL Server uses BEGIN and END to enclose blocks of code - not brackets (). So an IF should look like:
IF <Something>
BEGIN
--If block
END
ELSE
BEGIN
--Else block
END

What is the proper way to fill a form with multiple data fields?

I have been asked to create a vb.net WinForms app that automates the creation of this spreadsheet:
Obviously, creating that spreadsheet manually is a back breaking task.
I am very comfortable writing SQL to pull each individual field of data, however I've got to believe that there is a better way. Such a method would require 144 queries !!
I've considered creating a form with individual labels for each field, or using a gridview. Either would be acceptable to the end user, but I'm really not sure how I would write a query to produce a dataset that look like the end product anyway.
I'm not asking anyone to write any code for me, what I'm asking for help with is the concept of how I should attack this task.
Here is a query that I wrote which returns the fields for Business Unit #1 for the first week on the spreadsheet. I don't think it helps much, but I'm adding it to show that I've put some effort into this.
DECLARE #WeekEnding AS DATE
DECLARE #DIV AS INT
SET #WeekEnding = '11/13/2015'
SET #DIV = 20
-- A/R downpayments OPCH
SELECT
SUM(OPCH.DocTotal - OPCH.VatSum - OPCH.TotalExpns) AS 'ARDownPaymentInvoice'
FROM OPCH
LEFT JOIN INV1 ON OPCH.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0
LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode
LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod
LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode
WHERE DATEPART(WEEK, OPCH.DocDate) = DATEPART(WEEK, #WeekEnding) AND YEAR(OPCH.DocDate) = YEAR(#WeekEnding)
AND CurrCode.Segment_4 = #DIV
-- Credits ORIN
SELECT
SUM(ORIN.DocTotal - ORIN.VatSum - ORIN.TotalExpns) * -1 AS 'Credit'
FROM ORIN
LEFT JOIN INV1 ON ORIN.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0
LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode
LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod
LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode
WHERE DATEPART(WEEK, ORIN.DocDate) = DATEPART(WEEK, #WeekEnding) AND YEAR(ORIN.DocDate) = YEAR(#WeekEnding)
AND CurrCode.Segment_4 = #DIV
--Invoices
SELECT
SUM(OINV.DocTotal - OINV.VatSum - OINV.TotalExpns) AS 'Invoice'
FROM OINV
LEFT JOIN INV1 ON OINV.DocEntry = INV1.DocEntry AND INV1.VisOrder = 0
LEFT JOIN OITM ON INV1.ItemCode = OITM.ItemCode
LEFT JOIN OITB ON OITM.ItmsGrpCod = OITB.ItmsGrpCod
LEFT JOIN OACT AS CurrCode (NOLOCK) ON OITB.RevenuesAc = CurrCode.AcctCode
WHERE DATEPART(WEEK, OINV.DocDate) = DATEPART(WEEK, #WeekEnding) AND YEAR(OINV.DocDate) = YEAR(#WeekEnding)
AND CurrCode.Segment_4 = #DIV`
Thanks for any ideas.
I would do a pivot rather than doing multiple queries. However I think you should ask yourself or the end user: "Do you really want to see an aging report by date as columns?" If so do I add one manually each time the report ages another increment? Here is a self extracting example FYI. The first set is just displaying my data where I mock up a user, a department they belong to, and their last access. Then I pretend I want a report of aging to see how many people access the system in total, and by each fictitious department. Doing multiple queries in SQL is expensive and can often be alleviated with a little know how of pivots, unions, and holding your data creatively with SQL.
DECLARE #Example TABLE (PersonId INT IDENTITY, PersonName VARCHAR(128), DepartmentName VARCHAR(128), AccessedOn Date);
INSERT INTO #Example (PersonName, DepartmentName, AccessedOn) VALUES ('Brett', 'Dev', '1-1-2017'), ('John', 'Dev', '1-6-2017'), ('Mark', 'Dev', '1-8-2017'), ('Shawn', 'Ops', '1-15-2017'), ('Ryan', 'Ops', '1-16-2017'), ('Kevin', 'Ops', '1-21-2017');
--Data as is
SELECT *
From #Example
--I would use Date By row as it is far easier to maintain
SELECT
DATEADD(WEEK, DATEDIFF(WEEK, 0, AccessedOn), 0) AS Grouping
, COUNT(PersonId) AS PeopleAccessedAtTime
, SUM(CASE WHEN DepartmentName = 'Dev' THEN 1 ELSE 0 END) AS DevCounts
, SUM(CASE WHEN DepartmentName = 'Ops' THEN 1 ELSE 0 END) AS OpsCounts
FROM #Example
GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, AccessedOn), 0)
--Aging Report you are asking for trouble as you need to manually pivot ELSE go down the road of doing dynamic sql to do a pivot which is No Bueno
; WITH x AS
(
SELECT
DATEADD(WEEK, DATEDIFF(WEEK, 0, AccessedOn), 0) AS Grouping
, COUNT(PersonId) AS PeopleAccessedAtTime
, SUM(CASE WHEN DepartmentName = 'Dev' THEN 1 ELSE 0 END) AS DevCounts
, SUM(CASE WHEN DepartmentName = 'Ops' THEN 1 ELSE 0 END) AS OpsCounts
FROM #Example
GROUP BY DATEADD(WEEK, DATEDIFF(WEEK, 0, AccessedOn), 0)
)
Select
'PeopleAccessed' AS Header
, MAX([2017-01-02]) AS [2017-01-02]
, Max([2017-01-09]) AS [2017-01-09]
, Max([2017-01-16]) AS [2017-01-16]
From x
PIVOT(MAX(PeopleAccessedAtTime) FOR Grouping IN ([2017-01-02], [2017-01-09], [2017-01-16])) AS pvt
UNION
Select
'DevDivisionAccessed'
, MAX([2017-01-02]) AS [2017-01-02]
, Max([2017-01-09]) AS [2017-01-09]
, Max([2017-01-16]) AS [2017-01-16]
From x
PIVOT(MAX(DevCounts) FOR Grouping IN ([2017-01-02], [2017-01-09], [2017-01-16])) AS pvt
UNION
Select
'OpsDivisionAccessed'
, MAX([2017-01-02]) AS [2017-01-02]
, Max([2017-01-09]) AS [2017-01-09]
, Max([2017-01-16]) AS [2017-01-16]
From x
PIVOT(MAX(OpsCounts) FOR Grouping IN ([2017-01-02], [2017-01-09], [2017-01-16])) AS pvt
One way to achieve this:
CREATE TABLE #tmpData
(column1 varchar(50),
column2 varchar(50),
column3 varchar(50),
column4 varchar(50),
column5 varchar(50),
column6 varchar(50),
column7 varchar(50),
column8 varchar(50),
column9 varchar(50),
column10 varchar(50),
column11 varchar(50),
column12 varchar(50))
Then you could insert a row displaying the dates of each column
INSERT INTO #tmpData
--Write your select query here for filling in all the dates
Then you would insert the data for each line item in the rows.
INSERT INTO #tmpdata
SELECT 'Business Unit 1',
-- insert remaining column data here

SQL Code working in SSMS but not in Report Builder 3.0

I have a code that works in SSMS but not in Report Builder. Tn the first part I create a temporary table and in the second i attach that table (using join) to my entire query. In SSMS i can do it declaring twice the parameters and using GO after the temporary table is created but RP Builder i cannot use go.
Below you can find the code.
Any hint is appreciated. Thank you!
IF OBJECT_ID('tempdb..#TempResTable') IS NOT NULL DROP TABLE #TempResTable
IF OBJECT_ID('tempdb..#Temp123') IS NOT NULL DROP TABLE #Temp123
declare #fromDate date
set #fromDate='2015-10-26'
declare #toDate date
set #toDate='2015-11-17'
Create table #tempResTable (id_resource int, Mins int)
while (#fromDate <= #toDate)
begin
Insert into #TempResTable
select
r.id_resource
,datediff(mi,coalesce(cw.from_time,convert(time, '12:00:00 AM')),coalesce(cw.till_time,convert(time , '23:59:59 PM'))) as 'MinutesAvailable'
from calendar
join resource r on r.id_calendar=calendar.id_calendar
left join calendarVersion cv on cv.id_calendarVersion=calendar.id_calendar
left join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
--where r.id_resource=#resource
where cw.id_availabilitykind in(2,8)
and cw.weekday=(case when (datediff(dd,cv.from_date,#fromDate)+1)-((datediff(dd,cv.from_date,#fromDate)+1)/(nofweeks*7)*(nofweeks*7))=0 then nofweeks*7
else (datediff(dd,cv.from_date,#fromDate)+1)-((datediff(dd,cv.from_date,#fromDate)+1)/(nofweeks*7)*(nofweeks*7))
end)
Group By r.id_resource
,cv.from_date
,cw.from_time
,cw.till_time,cw.id_availabilitykind
--)
set #fromDate=dateadd(dd,1,#fromDate)
end
go
declare #fromDate date
set #fromDate='2015-10-26'
declare #toDate date
set #toDate='2015-11-17'
select * into #temp123 from
(
select vwdepartment.departmentName
,row_number() over (order by resource.ID_resource) as 'rowNumber'
,resource.resourceName
,resource.id_resource
,B.AvailabilityHours
--,vwplannedShift.id_shift
--,vwplannedShift.plannedstartinstant
--,vwplannedShift.plannedfinishinstant
--,datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant)
, ( select sum(distinct(datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant))) from resource r1 where r1.resourceName=resource.resourceName group by r1.resourceName ) as 'MinsPlanned'
--,cw.from_time
--,cw.till_time
--,[dbo].[sp_ResourceAvailability]
from vwplannedShift
join vwshift on vwshift.id_shift = vwplannedShift.id_shift
and datediff(dd,#fromDate , vwplannedShift.plannedStartInstant) >=0
and datediff(dd,#toDate , vwplannedShift.plannedStartInstant) <=0
join vwdepartment on vwdepartment.id_department = vwplannedShift.id_department
join vwaction actions on coalesce(actions.t3_shift, actions.id_shift) = vwshift.id_shift
join vwresourceCombinationDriver driver on actions.id_unionResourceCombi = driver.id_resourceCombination
join resource on driver.id_resource = resource.id_resource
join resourceKind rk on rk.id_resourceKind=resource.id_resourceKind
join calendar c on c.id_calendar=resource.id_calendar
join calendarversion cv on cv.id_calendar=c.id_calendar
join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
left join availabilityKind ak on ak.id_availabilityKind=cw.id_availabilityKind and cw.id_availabilityKind in (2,8)
LEFT JOIN (select id_resource, sum(mins)AS AvailabilityHours from #tempResTable GROUP BY #tempResTable.id_resource) B ON B.ID_RESOURCE=RESOURCE.ID_RESOURCE
group by resource.resourcename,resource.id_resource,vwdepartment.departmentName,B.AvailabilityHours
union
select vwdepartment.departmentName
,row_number() over (order by resource.ID_resource) as 'rowNumber'
,resource.resourceName
,resource.id_resource
,B.AvailabilityHours
--,vwplannedShift.id_shift
--,vwplannedShift.plannedstartinstant
--,vwplannedShift.plannedfinishinstant
--,datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant)
,( select sum(distinct(datediff(mi,vwplannedShift.plannedstartinstant,vwplannedShift.plannedfinishinstant))) from resource r1 where r1.resourceName=resource.resourceName group by r1.resourceName ) as 'MinsPlanned'
--,cw.from_time
--,cw.till_time
from vwplannedShift
join vwshift on vwshift.id_shift = vwplannedShift.id_shift
and datediff(dd,#fromdate , vwplannedShift.plannedStartInstant) >=0
and datediff(dd,#todate , vwplannedShift.plannedStartInstant) <=0
join vwdepartment on vwdepartment.id_department = vwplannedShift.id_department
join vwaction actions on coalesce(actions.t3_shift, actions.id_shift) = vwshift.id_shift
join vwresourcecombinationtruck truck on actions.id_unionResourceCombi = truck.id_resourceCombination
join resource on truck.id_resource = resource.id_resource
join resourceKind rk on rk.id_resourceKind=resource.id_resourceKind
left join calendar c on c.id_calendar=resource.id_calendar
left join calendarversion cv on cv.id_calendar=c.id_calendar
left join calendarweekdayentry cw on cw.id_calendarVersion=cv.id_calendarVersion
left join availabilityKind ak on ak.id_availabilityKind=cw.id_availabilityKind and cw.id_availabilityKind in (2,8)
LEFT JOIN (select id_resource, sum(mins)AS AvailabilityHours from #tempResTable GROUP BY #tempResTable.id_resource) B ON B.ID_RESOURCE=RESOURCE.ID_RESOURCE
group by resource.resourcename,resource.id_resource,vwdepartment.departmentName,B.AvailabilityHours
) as cte
select* from #temp123
Quoting from the documentation on GO:
GO is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor.
So not recognized by Report Builder.
While TT has identified the problem with the code you have, the workaround would be to create a new Stored Procedure in the database, which will allow you to create, populate and interrogate temporary tables at will.
Something like this perhaps?
CREATE PROCEDURE [dbo].[GetMyData] ( #startDate DATETIME, #endDate DATEIME )
Create table #tempResTable (id_resource int, Mins int)
...
(All the rest of your code (without the variable declarations and 'GOs')
...
select* from #temp123
GO
GRANT EXECUTE ON [dbo].[GetMyData] TO [MyUser]
GO
Then reference this directly from your Dataset by choosing "Stored Procedure" instead of "Text"

Joining reports

I am trying to join 3 reports into one, taking parts out of each report.
This is my script that works with 2 of the reports:
ALTER VIEW [dbo].[v_JB2] AS
SELECT R.*, I.ENTERED, I.PROBLEM_CODE, I.WORKORDER
FROM DALE.DBO.V_JBTRB R
JOIN REPORTS.DBO.V_TC_ANALYSIS_JEREMY I
ON R.HUBID = I.HUB
AND R.NODEID = I.NODE
AND CAST(R.CREATE_DATE AS DATE) = I.ENTERED_DATE
GO
and I want to add this field A.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS from what should be DALE.DBO.V_MTTA
Your join of DALE.DBO.V_MTTA has no ON condition...
Try this:
SELECT R.*, I.ENTERED, I.PROBLEM_CODE, I.WORKORDER,
A.CREATE_DATE-O.ACTUAL_START_DATE as ASSIGN_SECS
FROM
DALE.DBO.V_JBTRB R JOIN
REPORTS.DBO.V_TC_ANALYSIS_JEREMY I
ON R.HUBID = I.HUB AND R.NODEID = I.NODE AND
CAST(R.CREATE_DATE AS DATE) = I.ENTERED_DATE
JOIN DALE.DBO.V_MTTA A ON A.CREATE_DATE-O.ACTUAL_START_DATE = ??? (what do you want this to be joined on? I don't know how your tables are related, but you need a valid ON statement for this join to work)
so the right answer was and i don't think anyone would have been able to tell based on the code was instead of joining a third query i added to my trb query and got the same data not sure why i didn't think of it sooner.
ALTER VIEW [dbo].[v_JBTRB] AS
SELECT SINGLE_USER, RECORD_ID, DIVISION, CREATE_DATETIMEINNEW, OUTAGESTARTDATE, STATUS_DESC, CAST(HUBID AS VARCHAR(255)) AS HUBID, CAST(NODEID AS VARCHAR(255)) AS NODEID, CATEGORY, STATUS, ASSIGN_SECS
FROM OPENQUERY(REMEDY_BI,
'
SELECT
T.RECORD_ID AS Record_ID
, T.DIVISION AS Division
, T.CREATE_DATE_ET AS Create_Date
, T.TIME_IN_NEW AS TimeInNew
, O.ACTUAL_START_DATE_ET AS OutageStartDate
, T.STATUS_DESC
, T.FACILITY AS HubID
, T.NODE AS NodeID
, T.CATEGORY
, T.STATUS
, T.SINGLE_USER
, T.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS
FROM ARNEUSER.VW_BASE_TROUBLE T
JOIN ARNEUSER.VW_BASE_OUTAGE O
ON O.INSTANCE_ID = T.OUTAGE_INSTANCE_ID
AND O.SUBMITTED_BY = T.SUBMITTER
JOIN ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS A
ON A.TROUBLE_ID = T.TROUBLE_ID
AND A.CREATE_DATE = ( SELECT MIN(CREATE_DATE)
FROM ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS
WHERE TROUBLE_ID=T.TROUBLE_ID
AND STATUS_NUM=1
AND CREATE_DATE>=O.ACTUAL_START_DATE
AND SUBMITTER=T.SUBMITTER )
WHERE T.STATUS > 3
AND T.REGION = ''Carolina''
AND T.CREATE_DATE >= DATE_TO_UNIX_TZ(TRUNC(SYSDATE)-14)
AND T.CATEGORY IN (''HFC'',''CRITICAL INFRASTRUCTURE'',''VIDEO DIGITAL'',''VIDEO ANALOG'',''DIGITAL PHONE'',''HEADEND/HUB'',''METRO/REGIONAL NETWORK'',''NATIONAL BACKBONE'',''NETWORK'')
')
I added this part the rest was already there if that helps this is one of the reports i was originally joining. I was trying to join another report but it came from the same data base.
, T.CREATE_DATE-O.ACTUAL_START_DATE AS ASSIGN_SECS
AND A.CREATE_DATE = ( SELECT MIN(CREATE_DATE)
FROM ARNEUSER.VW_BASE_TROUBLE_TKT_ASGN_HIS
WHERE TROUBLE_ID=T.TROUBLE_ID
AND STATUS_NUM=1
AND CREATE_DATE>=O.ACTUAL_START_DATE
AND SUBMITTER=T.SUBMITTER )
this is the other query that was being joined for anyone curious the 8 **** replace some sensitive data
ALTER VIEW [dbo].[v_TC_ANALYSIS_JEREMY] AS
SELECT *, cast(entered_date + ' ' + entered_time as datetime) as ENTERED FROM OPENQUERY(ICOMS_H,'
SELECT
W.WONUM AS WORKORDER,
W.WOTYC AS TYPE,
CVGDT2DATE(W.WOEDT) AS ENTERED_DATE,
W.WOQCD AS QUEUE_CODE,
W.WOETM AS TIME_ENTERED,
W.WOPB1 AS PROBLEM_CODE,
TRIM(H.HOAAEQ) AS HUB,
TRIM(H.HONODE) AS NODE,
H.HOZIP5 AS ZIPCODE,
W.WOPOL AS POOL,
P.EXTXD0 AS AREA,
CVGTM2TIME(W.WOETM) AS ENTERED_TIME
FROM
********.WOMHIPF W
JOIN ******.HOSTPF H ON H.HONUM = W.WOHNUM
JOIN CF83PF P ON P.EXPLLL = W.WOPOL
WHERE
W.WOEDT >= REPLACE(CHAR(CURRENT_DATE - 14 DAYS,ISO),''-'','''')-19000000
AND ((WOTYC =''SR'' AND WOQCD IN (''O'',''M'')) OR (WOTYC =''TC''))
AND WOPOL IN (''1'',''2'',''3'',''4'',''6'',''7'',''E'',''M'',''R'')

slow performance with exists case statement

Essentially I am trying to see if c_DSS_PG_Submission.PtNum is in the ED_MLP_ATTN temp table and if it is then assign 'MLP+ATTN'. The temp table alone takes about 2 minutes to generate and has ~1000 rows, the PG table has about ~300 rows so these are not big tables. However the query below runs for 20+ minutes. Would you recommend anything different with the query? I've tried changing exists to IN but same slow performance.
WITH ed_mlp_attn
AS ( SELECT smsdss.c_cfvhs_emstat_chart.visitno ,
CAST (smsdss.c_cfvhs_emstat_chart.dschdate AS DATE) AS dschdate
FROM smsdss.c_cfvhs_emstat_chart
INNER JOIN smsdss.c_cfvhs_emstat_oi_header ON smsdss.c_cfvhs_emstat_chart.chrtno = c_cfvhs_emstat_oi_header.chartno
COLLATE SQL_Latin1_General_Pref_CP1_CI_AS
INNER JOIN smsdss.c_cfvhs_emstat_oi_detail ON c_cfvhs_emstat_oi_header.oi_header_id = smsdss.c_cfvhs_emstat_oi_detail.oi_header_id
INNER JOIN smsdss.c_cfvhs_emstat_physician ON smsdss.c_cfvhs_emstat_chart.erphys = smsdss.c_cfvhs_emstat_physician.physid
COLLATE SQL_Latin1_General_Pref_CP1_CI_AS
WHERE smsdss.c_cfvhs_emstat_chart.dschdate >= DATEADD(mm, -1,
GETDATE())
AND smsdss.c_cfvhs_emstat_chart.dispocd <> 'DXERR'
AND c_cfvhs_emstat_oi_detail.VALUE IN ( '21504',
'21505' )
AND smsdss.c_cfvhs_emstat_physician.code1 = 'RES'
)
SELECT atndrname ,
atndrno ,
CASE WHEN EXISTS ( SELECT 1
FROM ed_mlp_attn
WHERE visitno COLLATE SQL_Latin1_General_Pref_CP1_CI_AS = smsdss.c_dss_pg_submission.ptnum )
THEN 'MLP+ATTN'
ELSE 'NO'
END AS ed_prov_type
FROM smsdss.c_dss_pg_submission
WHERE date_run = '2014-12-12'
AND surveydesignator IN ( 'ER0101', 'PE0101' )
ORDER BY surveydesignator ,
ptnum
Firstly, a CTE is not the same as a temp table, note the information in #JodyT's comment.
The query in the CTE will be executed for each row returned by outer query.
This will slow down the query a great deal I'd expect. I would break down the current CTE in to an actual temp table as a starting point to improve performance.
NOTE: I've used aliases for table names to reduce the amount of SQL and make it a little easier to read.
SELECT chart.visitno , CAST (chart.dschdate AS DATE) AS dschdate
INTO #TEMP
FROM c_cfvhs_emstat_chart chart
INNER JOIN c_cfvhs_emstat_oi_header header
ON chart.chrtno = header.chartno COLLATE SQL_Latin1_General_Pref_CP1_CI_AS
INNER JOIN c_cfvhs_emstat_oi_detail detail
ON header.oi_header_id = detail.oi_header_id
INNER JOIN c_cfvhs_emstat_physician physician
ON chart.erphys = physician.physid COLLATE SQL_Latin1_General_Pref_CP1_CI_AS
WHERE chart.dschdate >= DATEADD(mm, -1, GETDATE())
AND chart.dispocd <> 'DXERR'
AND detail.VALUE IN ( '21504', '21505' )
AND physician.code1 = 'RES'
Then query that:
SELECT atndrname ,
atndrno ,
CASE WHEN EXISTS ( SELECT 1
FROM #TEMP
WHERE visitno COLLATE SQL_Latin1_General_Pref_CP1_CI_AS = smsdss.c_dss_pg_submission.ptnum )
THEN 'MLP+ATTN'
ELSE 'NO'
END AS ed_prov_type
FROM smsdss.c_dss_pg_submission
WHERE date_run = '2014-12-12'
AND surveydesignator IN ( 'ER0101', 'PE0101' )
ORDER BY surveydesignator , ptnum
Breaking it down like this should improve performance by a degree, but without information on indexes and an execution plan, it's difficult to provide further advice.