SQL Stored Procedure Optional Parameter - sql

I am trying to create a Stored Procedure as follows -
CREATE PROCEDURE [dbo].[Chargeable_Time] #DateFrom DATE,
#DateTo DATE,
#Allocated INT = NULL
AS
SELECT t.CaseID,
c.DisplayNo,
c.CaseName,
c.[Category],
t.[Date],
t.FeeEarner,
u.Username,
t.ChargeCode,
t.[Hours],
t.Fees,
t.GroupID,
( CASE
WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END ) AS Allocated
FROM Timesheet AS t
LEFT JOIN [User] AS u
ON t.FeeEarner = u.ID
LEFT JOIN [Case] AS c
ON t.CaseID = c.ID
WHERE t.Active = 'True'
AND t.CaseID IS NOT NULL
AND t.Rate > 0
AND t.[Date] >= #DateFrom
AND t.[Date] <= #DateTo
AND Allocated = #Allocated
However I have two problems -
The Allocated field is not recognised as it is created by the procedure rather than being a field in the underlying tables, and
I want to be able to return all data if the Allocated field is left NULL. As it currently stands anyone calling the procedure can enter a 0 or 1 to filter the results, but I want them to also be able to leave the parameter blank and get the full set without the filter. I am not sure how to do this.
Any help would be greatly appreciated.

You can change the last part of the code as follows
Create PROCEDURE [dbo].[Chargeable_Time]
#DateFrom DATE,
#DateTo DATE,
#Allocated INT = NULL
AS
Begin
SELECT t.CaseID,
c.DisplayNo,
c.CaseName,
c.[Category],
t.[Date],
t.FeeEarner,
u.Username,
t.ChargeCode,
t.[Hours],
t.Fees,
t.GroupID,
( CASE
WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END ) AS Allocated
FROM Timesheet AS t
LEFT JOIN [User] AS u
ON t.FeeEarner = u.ID
LEFT JOIN [Case] AS c
ON t.CaseID = c.ID
WHERE t.Active = 'True'
AND t.CaseID IS NOT NULL
AND t.Rate > 0
AND t.[Date] >= #DateFrom
AND t.[Date] <= #DateTo
AND (( CASE
WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END ) = #Allocated OR #Allocated is null )
END
GO

This should do the trick. However this can be a bad solution when there is lot's of data. You should test that. Some reading about this kind of solution:
https://www.sqlskills.com/blogs/kimberly/high-performance-procedures/
CREATE PROCEDURE [dbo].[Chargeable_Time]
#DateFrom DATE,
#DateTo DATE,
#Allocated INT = NULL
AS
SELECT
t.CaseID,
c.DisplayNo,
c.CaseName,
c.[Category],
t.[Date],
t.FeeEarner,
u.Username,
t.ChargeCode,
t.[Hours],
t.Fees,
t.GroupID,
(CASE WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END
) AS Allocated
FROM Timesheet AS t
LEFT JOIN [User] AS u ON t.FeeEarner = u.ID
LEFT JOIN [Case] AS c ON t.CaseID = c.ID
WHERE t.Active = 'True'
AND t.CaseID IS NOT NULL
AND t.Rate > 0
AND t.[Date] >= #DateFrom
AND t.[Date] <= #DateTo
AND (CASE WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END
) = #Allocated
OR #Allocated IS NULL;

You can simplify your code by using CROSS APPLY:
CREATE PROCEDURE [dbo].[Chargeable_Time]
#DateFrom DATE,
#DateTo DATE,
#Allocated INT = NULL
AS
Begin
SELECT t.CaseID,
c.DisplayNo,
c.CaseName,
c.[Category],
t.[Date],
t.FeeEarner,
u.Username,
t.ChargeCode,
t.[Hours],
t.Fees,
t.GroupID,
a.Allocated
FROM Timesheet AS t
CROSS APPLY (VALUES (CASE WHEN t.GroupID IS NOT NULL THEN 1
WHEN t.GroupID IS NULL THEN 0
END )) As a(Allocated)
LEFT JOIN [User] AS u
ON t.FeeEarner = u.ID
LEFT JOIN [Case] AS c
ON t.CaseID = c.ID
WHERE t.Active = 'True'
AND t.CaseID IS NOT NULL
AND t.Rate > 0
AND t.[Date] >= #DateFrom
AND t.[Date] <= #DateTo
AND (#Allocated IS NULL OR a.Allocated = #Allocated)
END
GO

Related

SQL Execute one query of 2 based on condition

I have 2 working query that I need to use to generate a report, I have configured 4 parameters that user can choose and I want that if idarea=0 then first query is executed, else second one. I tried the following but give me an error because of the nested with... any help? Thanks
declare #DataDa as date='20210501';
declare #DataA as date='20210504';
declare #idUtilizzatore as int=0;
declare #idArea as int=0;
SELECT CASE WHEN ( #idArea=0 )
THEN (select dbaree.dbo.StoricoAree.Descr as Lettore,
TIMBACCESSI.CODICEBADGE,
COGNOME as Cognome,NOME as Nome,
AZIENDE.DESCR as Azienda,FORMAT(DATAORA,'HH:mm') as Ora,
FORMAT(dataora,'dd/MM/yyyy') as Data,
iif(verso=0,'U','E') as Flusso from timbaccessi
join badge on badge.codice=timbaccessi.codicebadge
join anagrafico on anagrafico.ID=badge.IDUTILIZZATORE
join profilo on profilo.IDUTILIZZATORE=badge.IDUTILIZZATORE
join aziende on aziende.id=profilo.IDAZIENDA
join terminali on terminali.id=TIMBACCESSI.IDTERMINALE
join comparee on terminali.id=COMPAREE.IDTERMINALE
join dbAree.dbo.StoricoAree on storicoaree.idArea=COMPAREE.IDAREA
where (DATAORA>=#DataDa and DATAORA<#DataA) and (DATAORA >= dataDa and(DATAORA <= dataA or dataa is null)) and (badge.DATAFINE is null or badge.DATAFINE>=#DataA) AND (badge.idUtilizzatore = #IdUtilizzatore OR 0 = #IdUtilizzatore) AND (PROFILO.IDAZIENDA=#idAzienda OR 0 = #idAzienda) and (dbaree.dbo.StoricoAree.id=#idArea OR 0=#idArea)
group by dataora,cognome,nome,dbaree.dbo.StoricoAree.Descr,timbaccessi.CODICEBADGE,aziende.DESCR,timbaccessi.VERSO
ORDER BY Azienda asc, cognome asc, nome asc, Data asc, ora asc)
ELSE (with area as(
select t.CODICEBADGE as 'Numero tessera',
COGNOME as Cognome,NOME as Nome,
AZIENDE.DESCR as Azienda,FORMAT(DATAORA,'HH:mm') as Ora,
FORMAT(dataora,'dd/MM/yyyy') as Data,
iif(verso=0,'U','E') as Flusso, t.IDTERMINALE,t.DATAORA from timbaccessi t
join badge on badge.codice=t.codicebadge
join anagrafico on anagrafico.ID=badge.IDUTILIZZATORE
join profilo on profilo.IDUTILIZZATORE=badge.IDUTILIZZATORE
join aziende on aziende.id=profilo.IDAZIENDA
join terminali on terminali.id=t.IDTERMINALE
where (DATAORA>=#DataDa and DATAORA<#DataA)
and (badge.DATAFINE is null or badge.DATAFINE>=#DataA) AND (badge.idUtilizzatore = #IdUtilizzatore OR 0 = #IdUtilizzatore)
group by dataora,cognome,nome,t.CODICEBADGE,aziende.DESCR,t.VERSO,t.IDTERMINALE)
select a.[Numero tessera],a.Cognome,a.Nome,a.Azienda,a.Ora,a.Data,a.Flusso,s.Descr from area a join dbAree.dbo.StoricoAree s on s.id=#idArea where a.IDTERMINALE in (select idterminale from dbAree.dbo.termArea t join dbaree.dbo.StoricoAree s on s.id=t.idArea where t.idArea=#idArea and (#DataDa >= s.datada and (s.dataA is null or #DataDa < s.dataA)))
order by a.DATAORA )
END;
Just use IF:
IF (#idArea = 0)
BEGIN
<query1>;
END;
ELSE
<query 2>;
There is another way besides if that I've found useful. You can use union all and appropriately filter in your where statements.
It only makes sense when your output columns are the same number, order, and type. In your case, that's not true, but a very small modification can make it so:
declare #DataDa as date='20210501';
declare #DataA as date='20210504';
declare #idUtilizzatore as int=0;
declare #idArea as int=0;
with area as(
select t.CODICEBADGE as 'Numero tessera',
COGNOME as Cognome,NOME as Nome,
AZIENDE.DESCR as Azienda,
FORMAT(DATAORA,'HH:mm') as Ora,
FORMAT(dataora,'dd/MM/yyyy') as Data,
iif(verso=0,'U','E') as Flusso,
t.IDTERMINALE,t.DATAORA
from timbaccessi t
join badge on badge.codice=t.codicebadge
join anagrafico on anagrafico.ID=badge.IDUTILIZZATORE
join profilo on profilo.IDUTILIZZATORE=badge.IDUTILIZZATORE
join aziende on aziende.id=profilo.IDAZIENDA
join terminali on terminali.id=t.IDTERMINALE
where (DATAORA>=#DataDa and DATAORA<#DataA)
and (badge.DATAFINE is null or badge.DATAFINE>=#DataA)
AND (badge.idUtilizzatore = #IdUtilizzatore OR 0 = #IdUtilizzatore)
group by dataora,cognome,nome,t.CODICEBADGE,aziende.DESCR,t.VERSO,t.IDTERMINALE
)
select dbaree.dbo.StoricoAree.Descr as Lettore,
TIMBACCESSI.CODICEBADGE,
null as [Numero tessera], // not relevant unless #idArea <> 0
COGNOME as Cognome,
NOME as Nome,
AZIENDE.DESCR as Azienda,
FORMAT(DATAORA,'HH:mm') as Ora,
FORMAT(dataora,'dd/MM/yyyy') as Data,
iif(verso=0,'U','E') as Flusso,
null as Desc // not relevant unless #idArea <> 0
from timbaccessi
join badge on badge.codice=timbaccessi.codicebadge
join anagrafico on anagrafico.ID=badge.IDUTILIZZATORE
join profilo on profilo.IDUTILIZZATORE=badge.IDUTILIZZATORE
join aziende on aziende.id=profilo.IDAZIENDA
join terminali on terminali.id=TIMBACCESSI.IDTERMINALE
join comparee on terminali.id=COMPAREE.IDTERMINALE
join dbAree.dbo.StoricoAree on storicoaree.idArea=COMPAREE.IDAREA
where (DATAORA>=#DataDa and DATAORA<#DataA)
and (DATAORA >= dataDa and(DATAORA <= dataA or dataa is null))
and (badge.DATAFINE is null or badge.DATAFINE>=#DataA)
AND (badge.idUtilizzatore = #IdUtilizzatore OR 0 = #IdUtilizzatore)
AND (PROFILO.IDAZIENDA=#idAzienda OR 0 = #idAzienda)
and (dbaree.dbo.StoricoAree.id=#idArea OR 0=#idArea)
and #idArea = 0 // your case ////////////////////////////////////////
group by dataora,cognome,nome,dbaree.dbo.StoricoAree.Descr,
timbaccessi.CODICEBADGE,aziende.DESCR,timbaccessi.VERSO
union all
select null as Lettore, // not relevant unless #idArea = 0
null as CODICEBADGE, // not relevant unless #idArea = 0
a.Cognome,
a.Nome,
a.Azienda,
a.Ora,
a.Data,
a.Flusso,
s.Descr
from area a
join dbAree.dbo.StoricoAree s on s.id=#idArea
where a.IDTERMINALE in (
select idterminale
from dbAree.dbo.termArea t
join dbaree.dbo.StoricoAree s on s.id=t.idArea
where t.idArea=#idArea
and (
#DataDa >= s.datada and
(s.dataA is null or #DataDa < s.dataA)
)
order by a.DATAORA
)
and (#idArea <> 0 or #idArea is null) // your else /////////////////
ORDER BY Azienda asc, cognome asc, nome asc, Data asc, ora asc;
This has the advantage of keeping the result set predictable. If it's predictable, it can have some advantages. For instance, if desired, you could turn this into a table valued function. Or you could otherwise have other code that depends on it and won't break if the output has an unexpected structure.

UPDATE all records from existing SELECT query

I have query to select data from related tables.
SELECT
s.id,
CASE
WHEN count(DISTINCT e.id) <> 0
THEN count(DISTINCT o.id) / count(DISTINCT e.id)
END OrdersAverageNumber
FROM
[School] s
JOIN
[SchoolStore] ss ON ss.SchoolId = s.Id
JOIN
[Event] e ON e.SchoolId = ss.SchoolId
AND e.IsDeleted = 0
AND e.Status = 1
AND e.Date >= #startDate
AND e.Date <= #endDate
JOIN
[Order] o ON o.EventId = e.id
AND o.OrderStatus = 1
AND o.CreatedDate >= #startDate
AND o.CreatedDate <= #endDate
GROUP BY
s.id;
But I can't understand what I need to change to update all OrdersAverageNumber records in School table with values from selection above.
You can use update:
with q as (< your query here >)
update s
set OrdersAverageNumber = q.OrdersAverageNumber
from school s join
q
on s.id = q.id;

Stored Procedure Case statement override each other

This is the modified version of my previous post. please help me with this.
In case sub query i am getting correct result. but when i run full sp Alert case and Field case are overriding each other.
Getting null value in status field, can anyone explain what I am going wrong?
(CASE
WHEN EXISTS(SELECT [GunSerialNo] FROM [dbo].[ArmouryIssueGun]
WHERE aig.ModifiedOn IS NOT NULL
AND aig.CreatedOn IS NOT NULL)
THEN 'In Armory'
WHEN EXISTS(SELECT aig.GunSerialNo
FROM [dbo].[ArmouryIssueGun] AS aig
INNER JOIN (SELECT *
FROM
(SELECT GunSerialNo, DATEADD(HOUR, EstimatedTime, CreatedOn) AS TIME_ADDED
FROM [ArmouryIssueGun]) ag
WHERE ag.TIME_ADDED<GETUTCDATE()) abd ON abd.GunSerialNo = aig.GunSerialNo
WHERE aig.ModifiedOn IS NULL
AND aig.CreatedBy IS NOT NULL)
THEN 'Alert'
WHEN EXISTS (SELECT aig.GunSerialNo
FROM [dbo].[ArmouryIssueGun] AS aig
INNER JOIN (SELECT *
FROM
(SELECT GunSerialNo, DATEADD(HOUR, EstimatedTime, CreatedOn) AS TIME_ADDED
FROM [ArmouryIssueGun]) ag
WHERE ag.TIME_ADDED>GETUTCDATE()) abd ON abd.GunSerialNo = aig.GunSerialNo
WHERE aig.ModifiedOn IS NULL
AND aig.CreatedBy IS NOT NULL)
THEN 'In Field'
END) AS [Status],
FROM
[dbo].[CarryAndUseLicence] cl
INNER JOIN
[dbo].[Branch] b ON b.[BranchId] = cl.[BranchId]
INNER JOIN
[dbo].[Gun] gun ON cl.[GunSerialNo] = gun.[SerialNo]
INNER JOIN
[dbo].[ArmouryIssueGun] aig ON aig.[StaffId] = cl.[StaffId]
The problem is the double use of the alias aig. The alias in the Exists-query overrides the alias from the top query. As a result of this, the Exists-query does not include the current record but looks at the entire table.
How It works:
WHEN EXISTS(SELECT aig2.GunSerialNo
FROM [dbo].[ArmouryIssueGun] AS aig2
INNER JOIN (SELECT *
FROM
(SELECT GunSerialNo, DATEADD(HOUR, EstimatedTime, CreatedOn) AS TIME_ADDED
FROM [ArmouryIssueGun]) ag
WHERE ag.TIME_ADDED<GETUTCDATE()) abd ON abd.GunSerialNo = aig.GunSerialNo
WHERE aig2.ModifiedOn IS NULL
AND aig2.CreatedBy IS NOT NULL)
THEN 'Alert'
WHEN EXISTS (SELECT aig2.GunSerialNo
FROM [dbo].[ArmouryIssueGun] AS aig2
INNER JOIN (SELECT *
FROM
(SELECT GunSerialNo, DATEADD(HOUR, EstimatedTime, CreatedOn) AS TIME_ADDED
FROM [ArmouryIssueGun]) ag
WHERE ag.TIME_ADDED>GETUTCDATE()) abd ON abd.GunSerialNo = aig.GunSerialNo
WHERE aig2.ModifiedOn IS NULL
AND aig2.CreatedBy IS NOT NULL)
THEN 'In Field'
or shorter
WHEN EXISTS(SELECT *
FROM [ArmouryIssueGun]
WHERE GunSerialNo = aig.GunSerialNo
AND DATEADD(HOUR, EstimatedTime, CreatedOn) < GETUTCDATE()
AND ModifiedOn IS NULL
AND CreatedBy IS NOT NULL
)
THEN 'Alert'
WHEN EXISTS(SELECT *
FROM [ArmouryIssueGun]
WHERE GunSerialNo = aig.GunSerialNo
AND DATEADD(HOUR, EstimatedTime, CreatedOn) > GETUTCDATE()
AND ModifiedOn IS NULL
AND CreatedBy IS NOT NULL
)
THEN 'In Field'

How to combine two select query results into one result using sp?

I'm declaring two comparison dates, I want data from both dates. I'm using left join for combined propose but this is not correct way. I'm missing some data. Instead of left join which one is best for?
result
productid FirstQty SecondQty FirstProductRevenue SecondProductRevenue
COCAK117 1 2 1370.00 1440.00
COCAK632 1 2 1125.00 2250.00
COCAK656 1 NULL 795.00 NULL
COCAK657 1 2 720.00 2090.00
COCAK775 3 1 2475.00 825.00
I'm getting data from full of first table and matching productid from second table, but I want total productid's from both the tables.
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select t1.productid,t1.FirstQty,t2.SecondQty,t1.FirstProductRevenue,t2.SecondProductRevenue
from
(select op.Productid
, count(op.ProductId)as FirstQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t1
----Second duration for all associates-----
left join
(select op.Productid
, count(op.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
) t2 on t1.productid=t2.productid
END
You can try to get all data at once and then sum only date ranges that you want.
I could made some mistake here as I don't have your data structures.
However you should get the idea how you can implement it.
select op.Productid
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate then
1 else 0 end) FirstQty
, sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 then
1 else 0 end) SecondQty,
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
then op.Price*op.Quantity
else 0 end),0) as FirstProductRevenue
, Round(Sum( case when Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1
then op.Price*op.Quantity
else 0 end),0) as SecondProductRevenue
from Orderdetails od
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts) op on op.Orderid=od.Orderid
inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
where ( Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
Or Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate1 and #EndDate1 )
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
Group by op.Productid
Maybe this (simplified):
select coalesce(t1.productid, t2.productid) as productid, t1.FirstQty, t2.SecondQty, t1.FirstProductRevenue, t2.SecondProductRevenue
from
(select ...) t1
----Second duration for all associates-----
full join
(select ...) t2 on t1.productid = t2.productid
try this
you create a function as follows
CREATE FUNCTION OrderDetails (
#StartDate DATETIME,
#EndDate DATETIME
)
RETURNS #tblList TABLE
(
orderId VARCHAR(1000)
)
AS
BEGIN
select orderid
insert into #tblList
from Orderdetails od inner JOIN City ct ON od.RecipientCityName = ct.CityName
INNER JOIN Associates ass ON Ct.AssociateId = ass.AssociateId
Inner join HomepageRowWiseProducts hr on op.ProductId=hr.Productid
and (od.TransactionId IS NOT NULL or ltrim(od.TransactionId) != '')
and #Rowname=hr.HomepageRow_name and hr.status=1
where Convert(datetime,Convert(Varchar(50),od.DeliveryDate,101)) between #StartDate and #EndDate
return
end
then call the function in your stored procedure according to the date you are passing you don't miss any records
CREATE PROCEDURE [dbo].[Orders]
(
#StartDate DATETIME,
#EndDate DATETIME,
#StartDate1 DATETIME,
#EndDate1 DATETIME,
#Rowname VARCHAR(100),
#AssociateName VARCHAR(50)
)
--[Orders] '05/03/2015','05/03/2015','05/05/2015','05/07/2015','Most Gifted Cakes','all'
AS BEGIN
if(#AssociateName='all')
BEGIN
----First duration for all associates-----
select op1.Productid
, count(op.ProductId)as FirstQty
,count(op1.ProductId)as SecondQty
, Round(Sum(op.Price*op.Quantity),0) as FirstProductRevenue
, Round(Sum(op1.Price*op1.Quantity),0) as FirstProductRevenue
from (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate,#EndDate) od on opp.Orderid=od.Orderid ) op
inner join (select Distinct Orderid,productid,Price,Quantity from Orderproducts opp inner join [Your_ScemaName].[OrderDetails](#StartDate1,#EndDate1) od on opp.Orderid=od.Orderid ) op1
-- since 1=1 is always true you will get all data
on 1=1
Group by op.Productid
end
end

There is already an object named '#FutureDatedExclude' in the database

SELECT FutureDatedEmployeeRecordsKey INTO #FutureDatedExclude
FROM dbo.vwRptDimEmployee_FutureDated FD1
WHERE EXISTS (SELECT 1 FROM dbo.vwRptDimEmployeeAll EE1 WITH (NOLOCK)
WHERE FD1.EmployeeID = EE1.EmployeeID AND FD1.EmployeeRecord = EE1.EmployeeRecord
AND FD1.JobEffectiveDate = EE1.JobEffectiveDT AND FD1.JobEffectiveDateSequence = EE1.JobEffectiveDateSequence
AND FD1.ActionCode = EE1.ActionCode AND FD1.ActionReasonCode = EE1.ActionReasonCode)
declare #JobStartDate date = '07/01/2014', #JobEndDate date = '06/30/2015'
SELECT DISTINCT
E.LastName,
E.SecondLastName,
E.FirstName,
E.MiddleName,
E.PreferredName,
E.PreferredFirstName,
E.NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
E.EmployeeID,
E.LPN,
E.GPN,
E.EmployeeRecord,
E.JobEffectiveDT JobEffectiveDate,
E.JobEffectiveDateSequence,
E.ActionCode,
E.Action,
E.ActionDate,
E.ActionReasonCode,
AR.Description ActionReason,
E.EmployeeStatusCode,
E.EmployeeStatusDesc,
CASE WHEN YEAR(E.LeaveEffectiveDT) > 2100 THEN NULL ELSE E.LeaveEffectiveDT END LeaveEffectiveDate,
CASE WHEN YEAR(E.ExpectedReturnDate) > 2100 THEN NULL ELSE E.ExpectedReturnDate END ExpectedReturnDate,
E.FullPartTime,
E.ShiftCode FWACode,
E.Shift FWAName,
E.TeleWork,
E.StandardHoursFrequency,
E.StandardHours,
E.FTE,
E.PaidFTE,
E.OvertimeEligibility,
E.EmployeeClassCode,
E.EmployeeClass,
E.RegularVersusTemporary RegularTemporary,
E.EmployeeType,
E.PersonnelStatusDesc,
E.PersonOrganizationRelationshipCode,
P.PersonOfInterest,
P.PersonOfInterestDesc,
E.PaygroupCode,
E.EmployeeCategoryCode,
E.EmployeeSubcategoryCode,
P.EmploymentCategory,
E.NonEmployeeNonWorkTypeCD NonEmployeeNonWorkTypeCode,
P.NonEmployeeNonWorkTypeDesc,
A.GlobalAssignmentProgramCD GlobalAssignmentProgramCode,
A.GlobalAssignmentProgramDesc,
CASE WHEN YEAR(E.GlobalAssignmentStartDT) > 2100 THEN NULL ELSE E.GlobalAssignmentStartDT END GlobalAssignmentStartDate,
CASE WHEN YEAR(E.GlobalAssignmentEndDT) > 2100 THEN NULL ELSE E.GlobalAssignmentEndDT END GlobalAssignmentEndDate,
E.InPatExPatStatus,
E.HomeCountry,
E.HomeHostCountry HostCountry,
CASE WHEN YEAR(E.EYStartDate) > 2100 THEN NULL ELSE E.EYStartDate END EYStartDate,
CASE WHEN YEAR(E.LastRehireDate) > 2100 THEN NULL ELSE E.LastRehireDate END LastRehireDate,
CASE WHEN YEAR(E.SeniorityDate) > 2100 THEN NULL ELSE E.SeniorityDate END SeniorityDate,
CASE WHEN YEAR(E.EmployeeEffectiveDate) > 2100 THEN NULL ELSE E.EmployeeEffectiveDate END CurrentEmploymentDate,
CASE WHEN YEAR(E.PartnerAdmissionDate) > 2100 THEN NULL ELSE E.PartnerAdmissionDate END PartnerAdmissionDate,
R.RankCDName RankCodeName,
E.Rank,
R.RankDesc,
E.BusinessTitle,--NEW
R.RankGroup1,--NEW
E.GFISRank,
E.ExperienceLevel,
E.GlobalGrade,
E.JobCode,--NEW
E.JobCDDesc JobCodeDesc,--NEW
E.DepartmentCode,
E.DepartmentName,
E.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
E.ManagerialCountryCD ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
E.CounselorGUI,--NEW
E.CounselorName,--NEW
E.BillRate,
E.Source,
--**** confidential fields ****
E.GenderCode,
E.TermCD TermCode,
E.TerminationReasonCode,
E.CompensationCurrency,
E.CompensationRate,
E.CompensationFrequency,
E.MonthlyCompensationRate,
E.AnnualCompensationRate,
CASE WHEN YEAR(P.SalaryEffectiveDT) > 2100 THEN NULL ELSE P.SalaryEffectiveDT END SalaryEffectiveDate,
E.SalaryAdminPlanCode,
E.SalaryAdminPlan,
E.SalaryGrade,
CASE WHEN YEAR(E.SalaryGradeEntryDate) > 2100 THEN NULL ELSE E.SalaryGradeEntryDate END SalaryGradeEntryDate,
NULL JobKEY,
NULL RowOrder
FROM dbo.vwRptFactEmployee F WITH (NOLOCK)
INNER JOIN dbo.vwRptDimEmployee E WITH (NOLOCK) ON (F.DimEmployeeKey = E.DimEmployeeKey)
INNER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (F.DimRankKey = R.DimRankKey)
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (F.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (F.DimLocationKey = L.DimLocationKey)
INNER JOIN dbo.vwRptDimAssignment A WITH (NOLOCK) ON (F.DimAssignmentKey = A.DimAssignmentKey)
--INNER JOIN dbo.vwRptDimDate D WITH (NOLOCK) ON (F.TransEffectiveDateKey = D.DimDateKey)
INNER JOIN dbo.vwRptDimEmployeeV2 P WITH (NOLOCK) ON (F.DimEmployeeKey = P.DimEmployeeKey)
LEFT OUTER JOIN (SELECT ActionCode, ActionReasonCode, Description, row_number() over (partition by ActionCode, ActionReasonCode order by EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfActionReason WITH (NOLOCK)) AR
ON (AR.ActionCode = E.ActionCode AND AR.ActionReasonCode = E.ActionReasonCode AND AR.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = E.CompanyCode AND C.RowOrder = 1)
WHERE (E.JobEffectiveDT BETWEEN #JobStartDate AND #JobEndDate)
-- AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (E.GPN = #GPN OR #GPN IS NULL)
--AND (E.GUI = #GUI OR #GUI IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (R.RankCD in (#RankCode) )
UNION
SELECT DISTINCT * FROM (
SELECT DISTINCT
ISNULL(E.LastName,N.LastName) LastName,
ISNULL(E.SecondLastName,N.SecondLastName) SecondLastName,
ISNULL(E.FirstName,N.FirstName) FirstName,
ISNULL(E.MiddleName,N.MiddleName) MiddleName,
E.PreferredName,
ISNULL(E.PreferredFirstName,N.PreferredFirstName) PreferredFirstName,
ISNULL(E.NameAC,N.NameAlternateCharacter) NameAC,
E.LastNameAC,
E.FirstNameAC,
E.MiddleNameAC,
E.GUI,
FD.EmployeeID,
FD.LPN,
FD.GPN,
FD.EmployeeRecord,
FD.JobEffectiveDate,
FD.JobEffectiveDateSequence,
FD.ActionCode,
FD.Action,
FD.ActionDate,
FD.ActionReasonCode,
FD.ActionReason,
FD.EmployeeStatusCode,
FD.EmployeeStatus,
NULL LeaveEffectiveDate,
CASE WHEN YEAR(FD.ExpectedReturnDate) > 2100 THEN NULL ELSE FD.ExpectedReturnDate END ExpectedReturnDate,
FD.FullPartTime,
FD.ShiftCode FWACode,
FD.Shift FWAName,
NULL Telework,
FD.StandardHoursFrequency,
NULL StandardHours,
FD.FTE,
FD.PaidFTE,
NULL OvertimeEligibility,
FD.EmployeeClassCode,
FD.EmployeeClass,
FD.RegularVersusTemporary RegularTemporary,
FD.EmployeeType,
NULL PersonnelStatusDesc,
FD.PersonOrganizationRelationshipCode,
NULL PersonOfInterest,
NULL PersonOfInterestDesc,
FD.PaygroupCode,
FD.EmployeeCategoryCode,
FD.EmployeeSubcategoryCode,
NULL EmploymentCategory,
NULL NonEmployeeNonWorkTypeCode,
NULL NonEmployeeNonWorkTypeDesc,
NULL GlobalAssignmentProgramCode,
NULL GlobalAssignmentProgramDesc,
NULL GlobalAssignmentStartDate,
NULL GlobalAssignmentEndDate,
NULL InPatExPatStatus,
NULL HomeCountry,
NULL HostCountry,
NULL EYStartDate,
NULL LastRehireDate,
NULL SeniorityDate,
NULL CurrentEmploymentDate,
NULL PartnerAdmissionDate,
R.RankCDName RankCodeName,
FD.Rank,
R.RankDesc,
FD.BusinessTitle,--NEW
R.RankGroup1,--NEW
FD.GFISRank,
NULL ExperienceLevel,
NULL GlobalGrade,
FD.JobCode,--NEW
NULL JobCodeDesc,--NEW
FD.DepartmentCode,
NULL DepartmentName,
FD.CompanyCode,
C.Description Company,
C.DescrAc CompanyAC,
NULL ManagerialCountry,
O.CodeBlock,
O.BUCD BU,
O.OUCD OU,
O.MUCD MU,
O.SMUCD SMU,
O.BUName,
O.OUName,
O.MUName,
O.SMUName,
O.UserDefSLHierarchy1 ServiceLine,
O.UserDefSLHierarchy2 SubSL1,
O.UserDefSLHierarchy3 SubSL2,
O.AlternateServiceLine,
O.UserDefAreaHierarchy1 BULevel1,
O.UserDefAreaHierarchy2 BULevel2,
O.UserDefAreaHierarchy3 BULevel3,
L.Location LocationCode,
L.City LocationCity,
L.State LocationStateProv,
L.Country LocationCountry,
L.UserDefinedHRGeo1 GeoLevel1,
L.UserDefinedHRGeo2 GeoLevel2,
L.UserDefinedHRGeo3 GeoLevel3,
L.UserDefinedHRGeo4 GeoLevel4,
L.UserDefinedHRGeo5 GeoLevel5,
NULL CounselorGUI,--NEW
NULL CounselorName,--NEW
NULL BillRate,
FD.Source,
--**** confidential fields ****
NULL GenderCode,
NULL TermCode,
FD.TerminationReasonCode,
FD.CompensationCurrency,
FD.CompensationRate,
FD.CompensationFrequency,
FD.MonthlyCompensationRate,
FD.AnnualCompensationRate,
NULL SalaryEffectiveDate,
FD.SalaryAdminPlanCode,
FD.SalaryAdminPlan,
FD.SalaryGrade,
CASE WHEN YEAR(FD.SalaryGradeEntryDate) > 2100 THEN NULL ELSE FD.SalaryGradeEntryDate END SalaryGradeEntryDate,
FD.Job_KEY,
row_number() over (partition by FD.EmployeeID, FD.EmployeeRecord, FD.JobEffectiveDate,
FD.JobEffectiveDateSequence, FD.ActionCode, FD.ActionReasonCode order by FD.Job_KEY DESC) as RowOrder
FROM dbo.vwRptDimEmployee_FutureDated FD
INNER JOIN dbo.vwRptDimOrganization O WITH (NOLOCK) ON (FD.DimOrganizationKey = O.DimOrganizationKey)
INNER JOIN dbo.vwRptDimLocation L WITH (NOLOCK) ON (FD.DimLocationKey = L.DimLocationKey)
LEFT OUTER JOIN dbo.vwRptDimRank R WITH (NOLOCK) ON (FD.Rank = R.RankCD)
LEFT OUTER JOIN dbo.vwRptDimEmployeeAll E WITH (NOLOCK) ON (FD.GPN = E.GPN AND FD.GPN <> '' AND E.RowIsCurrent = 'Y')
LEFT OUTER JOIN (SELECT *, ROW_NUMBER() OVER (PARTITION BY EmployeeID, NameType ORDER BY EffectiveDate DESC) AS RowOrder
FROM PISupport.vwRptPersonACNames WITH (NOLOCK)
) N ON (N.EmployeeID = FD.EmployeeID AND N.NameType = 'PRI' AND N.CountryNameFormat = FD.SetIDLaborAgreement AND N.RowOrder = 1)
LEFT OUTER JOIN (SELECT DISTINCT C1.*, ROW_NUMBER() OVER (PARTITION BY CompanyCode ORDER BY EffectiveDate DESC) as RowOrder
FROM PISupport.vwRptSetfCompany C1 WITH (NOLOCK)) C
ON (C.CompanyCode = FD.CompanyCode AND C.RowOrder = 1)
WHERE
FD.JobEffectiveDate BETWEEN #JobStartDate AND #JobEndDate
AND FD.EDWIsCurrentRecord = 1
AND FD.EmployeeID IS NOT NULL
--AND (E.ActionCode in ('ADD','DTA','HIR','POI','REH','PER','TER'))
--AND (O.BUCD+O.OUCD+O.MUCD+O.SMUCD LIKE '%'+#CodeBlock+'%' OR #CodeBlock IS NULL)
--AND (FD.GPN = #GPN OR #GPN IS NULL)
--AND (L.UserDefinedHRGeo1 in (#GeoArea) )
AND (L.UserDefinedHRGeo2 in ('UK and Ireland'))
--AND (L.UserDefinedHRGeo3 in (#Country) )
--AND (O.UserDefAreaHierarchy1 in (#Area) )
--AND (O.UserDefAreaHierarchy2 in (#Region) )
--AND (O.UserDefSLHierarchy1 in (#ServiceLine) )
--AND (O.UserDefSLHierarchy2 in (#SubServiceLine) )
--AND (FD.Rank in (#RankCode) )
AND FD.FutureDatedEmployeeRecordsKey NOT IN (SELECT FutureDatedEmployeeRecordsKey FROM #FutureDatedExclude)
) X
WHERE RowOrder = 1
DROP TABLE #FutureDatedExclude
You most likely ran this code before you added the DROP TABLE at the bottom of your code. Therefore, the table is created and yet to be dropped. Instead of dropping it at the end, or in addition to dropping it if you want, place this at the very top of your script:
IF OBJECT_ID('tempdb..#FutureDatedExclude') IS NOT NULL DROP TABLE #FutureDatedExclude