I want to get data historical and the production. My stored procedure is as follows:
ALTER PROCEDURE [dbo].[pCaRptACInactivas](
#CodAsesor VARCHAR(15),
#CodOficina VARCHAR(4))
AS
SET NOCOUNT ON
DECLARE #CodArbolConta VARCHAR(25)
IF #CodOficina = '%'
SET #CodArbolConta = '%'
ELSE
SELECT #CodArbolConta = CodArbolConta + '%' FROM tClOficinas WHERE CodOficina LIKE #CodOficina
SELECT
tabACInactivas.CodOficina,
tabACInactivas.NomOficina,
tabACInactivas.NomAsesor,
MAX(tabACInactivas.CodPrestamo) CodPrestamo,
tabACInactivas.CodAsociacion,
tabACInactivas.NombreAsociacion,
MAX(tabACInactivas.Ciclo) AS Ciclo,
COUNT(DISTINCT tabACInactivas.CodUsuario) AS CantSocias,
MAX(tabACInactivas.FechaEstado) AS FechaCancelacion--,
FROM ( SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaPrestamos.Ciclo, tCaPrCliente.CodUsuario, tCaPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaPrestamos.CodAsociacion INNER JOIN tCaPrCliente WITH(NOLOCK) ON tCaPrCliente.CodPrestamo = tCaPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaPrestamos Pr
INNER JOIN tCaPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaPrestamos.CodAsesor LIKE #CodAsesor AND tCaPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
UNION ALL
SELECT tClOficinas.CodOficina, tClOficinas.NomOficina, tCaClAsesores.CodAsesor, tCaClAsesores.NomAsesor, tCaHPrestamos.CodPrestamo, tCaAsociacion.CodAsociacion, tCaAsociacion.NombreAsociacion, tCaHPrestamos.Ciclo, tCaHPrCliente.CodUsuario, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso FROM tCaHPrestamos WITH(NOLOCK) INNER JOIN tCaProducto WITH(NOLOCK) ON tCaProducto.CodProducto = tCaHPrestamos.CodProducto INNER JOIN tClOficinas WITH(NOLOCK) ON tClOficinas.CodOficina = tCaHPrestamos.CodOficina INNER JOIN tCaAsociacion WITH(NOLOCK) ON tCaAsociacion.CodAsociacion = tCaHPrestamos.CodAsociacion INNER JOIN tCaHPrCliente WITH(NOLOCK) ON tCaHPrCliente.CodPrestamo = tCaHPrestamos.CodPrestamo INNER JOIN tClParametros WITH(NOLOCK) ON tClParametros.CodOficina = tClOficinas.CodOficina INNER JOIN tCaClAsesores ON tCaClAsesores.CodAsesor = tCaAsociacion.CodAsesor WHERE tCaHPrestamos.Estado = 'CANCELADO' AND DATEDIFF(DAY, tCaHPrestamos.FechaEstado, tClParametros.FechaProceso) > 30 AND NOT EXISTS(SELECT 1
FROM tCaHPrestamos Pr
INNER JOIN tCaHPrCliente PrCl ON PrCl.CodPrestamo = Pr.CodPrestamo
WHERE Pr.Estado NOT IN ('TRAMITE', 'APROBADO')
AND Pr.FechaDesembolso >= tCaHPrestamos.FechaEstado
AND Pr.CodAsociacion = tCaHPrestamos.CodAsociacion
) AND tCaProducto.Tecnologia = 3 AND tCaHPrestamos.CodAsesor LIKE #CodAsesor AND tCaHPrestamos.CodOficina IN (SELECT CodOficina FROM tClOficinas WHERE CodArbolConta LIKE #CodArbolConta)
)tabACInactivas
GROUP BY tabACInactivas.CodAsociacion, tabACInactivas.NombreAsociacion, tabACInactivas.NomOficina, tabACInactivas.CodOficina, tabACInactivas.NomAsesor
I want the CantSocias column takes the most value of the Ciclo column, but not working
That stored procedure that you have posted up is way too large and blocky to even try to interpret and understand. So I will go off of your last sentence:
I want the CantSocias column takes the most value of the Ciclo column,
but not working
Basically if you want to set a specific column to that, you can do something like this:
update YourTable
set CantSocias =
(
select max(Ciclo)
from YourOtherTable
)
-- here is where you can put a conditional WHERE clause
You may need to create a sub query to get the most value of Ciclo and join back to your query.
An example of what I mean is here:
create table #Product
(
ID int,
ProductName varchar(20)
)
insert into #Product(ID, ProductName)
select 1,'ProductOne'
union
select 2,'ProductTwo'
create table #ProductSale
(
ProductID int,
Number int,
SalesRegion varchar(20)
)
insert into #ProductSale(ProductID,Number,SalesRegion)
select 1,1500,'North'
union
select 1, 1200, 'South'
union
select 2,2500,'North'
union
select 2, 3200, 'South'
--select product sales region with the most sales
select * from #Product p
select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID
--combining
select
p.ID,
p.ProductName,
tp.Bestsale,
ps.SalesRegion
from
#Product p
inner join
(select ProductId, Max(Number) as Bestsale from #ProductSale ps group by ProductID) as tp on p.ID = tp.ProductID
inner join
#ProductSale ps on p.ID = ps.ProductID and tp.Bestsale = ps.Number
Related
I have a stored procedure that checks if a record exist and if true then should update else it should insert. But for some weird reason the update does not work and it inserts a record. As a result I have now accumulated duplicate records in the table. How do I ensure that the update works separately from the insert.
CREATE PROCEDURE [dbo].[proc_CustomerAnalysis_Insert]
(
#CustomerID INT,
#UserID INT,
#ProcessCompleted BIT,
#DeliveryDate DATETIME,
#HasOpsNote BIT,
#OpsNote VARCHAR(500),
#isManual BIT,
#FinalStageID INT,
#EffectiveDate DATE,
#Outcome VARCHAR(50),
#ExculdeFromReview BIT
)
AS
BEGIN
DECLARE #TempCustomerAnalysis TABLE
(
CustomerID INT ,
IncreaseDate DATETIME,
Ref VARCHAR(50),
RateIncreaseID INT,
rn INT
)
IF EXISTS(SELECT CustomerID FROM DUmmy9 WHERE DUmmy9.CustomerID = #CustomerID)
BEGIN
WITH UpdateData AS
(
SELECT DISTINCT *
FROM (
SELECT
c.CustomerID CustomerID,
ri.RateIncreasePeriod IncreaseDate,
CONCAT(c.FWRepCode, '\', c.AccountCode) Ref,
ri.RateIncreaseID RateIncreaseID,
u.Name,
row_number() OVER(PARTITION BY c.Name ORDER BY ri.RateIncreasePeriod DESC) AS rn
FROM customers c
left outer join DUmmy1 rc on rc.RateClassID = c.RateClassID
left outer join DUmmy2 css on css.CustomerStatusID = c.CustomerStatusID
left outer join DUmmy3 ri on ri.RateCycleID = rc.RateCycleID
left outer join DUmmy4 fwrm ON fwrm.FWCode = c.FWRepCode
left outer join DUmmy5 rcs ON rcs.RepCodeID = fwrm.RepCodeID
left outer join DUmmy6 u ON u.UserID = rcs.UserID
left outer join DUmmy7 vw on vw.CustomerID = c.CustomerID
WHERE c.CustomerStatusID = 3 AND u.UserID = #UserID AND c.CustomerID = #CustomerID
) t
WHERE t.rn = 1
)
UPDATE DUmmy7
SET IncreaseDate = DUmmy8.IncreaseDate, Ref = DUmmy8.Ref, RateIncreaseID = DUmmy8.RateIncreaseID
FROM UpdateData
WHERE DUmmy8.CustomerID = #CustomerID
END
ELSE
BEGIN
INSERT INTO #TempCustomerAnalysis(CustomerID, IncreaseDate, Ref, RateIncreaseID, rn)
SELECT DISTINCT *
FROM (
SELECT
c.CustomerID CustomerID,
ri.RateIncreasePeriod IncreaseDate,
CONCAT(c.FWRepCode, '\', c.AccountCode) Ref,
ri.RateIncreaseID RateIncreaseID,
row_number() OVER(PARTITION BY c.Name ORDER BY ri.RateIncreasePeriod DESC) AS rn
FROM customers c
left outer join DUmmy1 rc on rc.RateClassID = c.RateClassID
left outer join DUmmy2 css on css.CustomerStatusID = c.CustomerStatusID
left outer join DUmmy3 ri on ri.RateCycleID = rc.RateCycleID
left outer join DUmmy4 fwrm ON fwrm.FWCode = c.FWRepCode
left outer join DUmmy5 rcs ON rcs.RepCodeID = fwrm.RepCodeID
left outer join DUmmy6 u ON u.UserID = rcs.UserID
left outer join DUmmy7 vw on vw.CustomerID = c.CustomerID
WHERE c.CustomerStatusID = 3 AND u.UserID = #UserID AND c.CustomerID = #CustomerID
) t
WHERE t.rn = 1
INSERT INTO DUmmy9(CustomerID, IncreaseDate, ProcessCompleted, DeliveryDate, Ref, HasOpsNote, OpsNote, RateIncreaseID, isManual, FinalStageID, EffectiveDate, Outcome, ExcludeFromReview)
SELECT
CustomerID,
IncreaseDate,
#ProcessCompleted,
#DeliveryDate,
Ref,
#HasOpsNote,
#OpsNote,
RateIncreaseID,
#isManual,
#FinalStageID,
#EffectiveDate,
#Outcome,
#ExculdeFromReview
FROM #TempCustomerAnalysis
END
END
From looking at your example. You never set CustomerAnalysis.CustomerID = #CustomerID before you check the IF ELSE, so that value is always NULL/ never exists in the CustomerAnalysis so ALWAYS goes into the ELSE.
DECLARE #CustomerIDExist INT = (SELECT COUNT(CustomerID) FROM CustomerAnalysis WHERE CustomerAnalysis.CustomerID = #CustomerID)
IF (#CustomerIDExist >= 1)
BEGIN
My Query IS
SELECT TblPharmacyBillingDetails.UPBNo, TblMasterBillingData.IPDNo, InPatRegistration.PatTitle+PatientName, TblPharmacyBillingDetails.InvoiceNo, TblPharmacyBillingDetails.InvoiceDateTime, TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
but if TblMasterBillingData.IPDNo value is NULL select Data From TblMasterBillingData.OPDNo and
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.IPDNo
Method #1: Using UNION
SELECT * FROm
(
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.IPDNo,
InPatRegistration.PatTitle+PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo
WHERE TblMasterBillingData.IPDNo IS NOT NULL
UNION ALL
SELECT TblPharmacyBillingDetails.UPBNo,
TblMasterBillingData.OPDNo,
OutPatRegistration .PatTitle + PatientName,
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.OPDNo
WHERE TblMasterBillingData.OPDNo IS NOT NULL
)Tmp
ORDER BY TblPharmacyBillingDetails.UPBNo
Method #2 Using ISNULL and LEFT JOIN
SELECT TblPharmacyBillingDetails.UPBNo,
ISNULL(TblMasterBillingData.IPDNo,TblMasterBillingData.OPDNo),
ISNULL(IP.PatTitle + IP.PatientName, OP.PatTitle + OP.PatientName),
TblPharmacyBillingDetails.InvoiceNo,
TblPharmacyBillingDetails.InvoiceDateTime,
TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
LEFT JOIN InPatRegistration IP ON TblMasterBillingData.IPDNo = IP.IPDNo
LEFT JOIN outPatRegistration OP ON TblMasterBillingData.OPDNo = OP.OPDNo
ORDER BY TblPharmacyBillingDetails.UPBNo
You can write either case statement or ISNULL() function as shown below in the demo query.
SELECT
Orders.OrderID,
Case when Customers1.CustomerName is null then Customers2.CustomerName else Customers1.CustomerName
end as CustomerName, --way 1
ISNULL(Customers1.CustomerName, Customers2.CustomerName) as Customer, --way 2
Orders.OrderDate
FROM Orders
INNER JOIN Customers1 ON Orders.CustomerID = Customers1.CustomerID
INNER JOIN Customers2 ON Orders.CustomerID = Customers2.CustomerID
-- where your condition here
-- order by your column name
You can also check whether data is available or not in the table and join the table accordingly using if exists as shown below.
if exists(select 1 from tablename where columnname = <your values>)
I have this stored procedure
CREATE PROCEDURE Research
(#ExamenId INT = NULL)
AS
BEGIN
CREATE TABLE #EXAMENS (PRESC_ID int, DEMANDE_ID int, EXAMEN_ID int)
IF (#ExamenId IS NOT NULL)
BEGIN
INSERT INTO #EXAMENS (PRESC_ID, DEMANDE_ID, EXAMEN_ID)
SELECT
OPI.PRESC_ID, PRPED.DEMANDE_ID, PRPE.EXAMEN_ID
FROM
PG_RADIO_PRESC_EXAMEN PRPE WITH (NOLOCK)
INNER JOIN
OPIUM_PRESC_ITEM OPI WITH (NOLOCK) ON OPI.ITEM_ID = PRPE.ITEM_ID
LEFT JOIN
PG_RADIO_PRESC_EXD_DEM PRPED WITH (NOLOCK) ON PRPED.EXAMEN_ID = PRPE.EXAMEN_ID
WHERE
PRPE.EXAMEN_ID = #ExamenId
END
SELECT
tes.EXAMEN_ID, tes.PARAMETRE_ID,
TXT_CODE_ID, VALEUR
FROM
(SELECT
PRPE.EXAMEN_ID, PRPEG.ParametreEntreeId AS PARAMETRE_ID,
0 AS TXT_CODE_ID,
ISNULL(Replace(CAST(pfs.FORM_SOURCE_SAISIE AS VARCHAR(MAX)), '', ''), Replace(CAST(pf.FORM_SOURCE AS VARCHAR(MAX)), '', '')) AS VALEUR
FROM
#EXAMENS tmpexam WITH (NOLOCK)
INNER JOIN
PG_RADIO_PRESC_EXAMEN PRPE WITH (NOLOCK) ON PRPE.EXAMEN_ID = tmpexam.EXAMEN_ID
INNER JOIN
PG_RADIO_PARAMETRE_ENTREE_GESTE PRPEG ON PRPEG.GesteId = PRPE.GESTE_ID
INNER JOIN
PG_PARAM_ENTREE_FORMULAIRE pf ON pf.PARAMETRE_ID = PRPEG.ParametreEntreeId
LEFT JOIN
PG_PARAM_ENTREE_FORMULAIRE_SAISI pfs ON pfs.EXAMEN_ID = tmpexam.EXAMEN_ID
AND pfs.PARAMETRE_ID = PRPEG.ParametreEntreeId) AS tes
LEFT JOIN
PG_PARAM_ENTREE_PARAMETRE ps ON ps.PARAMETRE_ID = tes.PARAMETRE_ID
ORDER BY
ps.RANG ASC
END
It returns EXAMEN_ID, PARAMETRE_ID, TXT_CODE_ID, VALEUR for one exam.
Now I want to pass a list of ids as varchar and for each id return its information EXAMEN_ID, PARAMETRE_ID, TXT_CODE_ID, VALEUR.
Thank you
Hi all is there any way that i can use multiple values in between clause as
column_name between 0 and 100 or 200 and 300 like this
Any help would be appreciated
here is my query SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
i just want to append multiple values in between clause
This is full query
SELECT ROW_NUMBER() OVER
(
order by Vendor_PrimaryInfo.Vendor_ID asc
)AS RowNumber
, Unit_Table.Unit_title, Vendor_Base_Price.Base_Price, Vendor_Base_Price.showprice, Category_Table.Title, Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address, Vendor_PrimaryInfo.Locality, Vendor_PrimaryInfo.Nearest_Landmark, Vendor_PrimaryInfo.City, Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country, Vendor_PrimaryInfo.PostalCode, Vendor_PrimaryInfo.Latitude, Vendor_PrimaryInfo.Longitude, Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo, Vendor_PrimaryInfo.Email,Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table INNER JOIN
Vendor_Base_Price ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID INNER JOIN
Vendor_PrimaryInfo ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID INNER JOIN
Vendor_Registration ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID AND
Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID INNER JOIN
Category_Table ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN
Vendor_Value_Table ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID LEFT JOIN
Feature_Table ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
where Vendor_Registration.Category_ID=5 and Vendor_PrimaryInfo.City='City'
AND(
value_text in('Dhol Wala$Shahnai Wala')
or
(SELECT CASE WHEN ISNUMERIC(value_text) = 1 THEN CAST(value_text AS INT) ELSE -1 END) between 0 and 100
)
You can do this using AND/OR logic
value_text NOT LIKE '%[^0-9]%' and
(
value_text between 0 and 100
Or
value_text between 101 and 200
)
If you don't want to repeat the column name then frame the range in table valued constructor and join with your table
SELECT Row_number()
OVER (
ORDER BY Vendor_PrimaryInfo.Vendor_ID ASC )AS RowNumber,
Unit_Table.Unit_title,
Vendor_Base_Price.Base_Price,
Vendor_Base_Price.showprice,
Category_Table.Title,
Vendor_Registration.Business_Name,
Vendor_PrimaryInfo.Street_Address,
Vendor_PrimaryInfo.Locality,
Vendor_PrimaryInfo.Nearest_Landmark,
Vendor_PrimaryInfo.City,
Vendor_PrimaryInfo.State,
Vendor_PrimaryInfo.Country,
Vendor_PrimaryInfo.PostalCode,
Vendor_PrimaryInfo.Latitude,
Vendor_PrimaryInfo.Longitude,
Vendor_PrimaryInfo.ImageUrl,
Vendor_PrimaryInfo.ContactNo,
Vendor_PrimaryInfo.Email,
Vendor_PrimaryInfo.Vendor_ID
FROM Unit_Table
INNER JOIN Vendor_Base_Price
ON Unit_Table.Unit_ID = Vendor_Base_Price.Unit_ID
INNER JOIN Vendor_PrimaryInfo
ON Vendor_Base_Price.Vendor_ID = Vendor_PrimaryInfo.Vendor_ID
INNER JOIN Vendor_Registration
ON Vendor_Base_Price.Vendor_ID = Vendor_Registration.Vendor_ID
AND Vendor_PrimaryInfo.Vendor_ID = Vendor_Registration.Vendor_ID
INNER JOIN Category_Table
ON Vendor_Registration.Category_ID = Category_Table.Category_ID
LEFT JOIN Vendor_Value_Table
ON Vendor_Registration.Vendor_ID = Vendor_Value_Table.Vendor_ID
LEFT JOIN Feature_Table
ON Vendor_Value_Table.Feature_ID = Feature_Table.Feature_ID
JOIN (VALUES (0, 100),
(101, 200),
(201, 300)) tc (st, ed)
ON Try_cast(value_text AS INT) BETWEEN st AND ed
OR Try_cast(value_text AS VARCHAR(100)) = 'Dhol Wala$Shahnai Wala'
WHERE Vendor_Registration.Category_ID = 5
AND Vendor_PrimaryInfo.City = 'City'
Note : You have stored two different information's in a single column which causes lot of pain when you want to extract the data like this. Consider changing your table structure
So my stored procedure has a staff column that should be generating a staff name from my Employee table. The staff name only shows up on for some of the rows. Can anyone take a look and see where my error is here:
BEGIN
IF EXISTS (SELECT 1 FROM [user] (NOLOCK)
WHERE [user].ID = #UserID
AND [user].BrandID IS NULL AND [user].SpaID IS NULL)
BEGIN
DECLARE #OrderStatusID_Completed int, #OrderStatusID_Shipped int
SET #OrderStatusID_Shipped = 4
SET #OrderStatusID_Completed = 2
SELECT
CAST('' AS varchar(50)) AS ErrMsg
, o.OrderNumber
, Customer.GUID AS CustomerGUID
, OrderItem_View.DateCreated AS ItemDate
, COALESCE(MasterProductVariant.SKU, ProductVariant.SKU, Treatment.SKU) AS SKU
, DynamicPrice.FinalPrice AS Price
--, COALESCE(MasterProductVariant.OriginalPrice, ProductVariant.OriginalPrice, Treatment.Price) AS Price
, ISNULL(Employee.FirstName,'') + ' ' + ISNULL(Employee.LastName,'') AS Staff
, COALESCE(Product.Name, Treatment.Name) AS Item
, NULL AS Note
FROM
[Order] o (Nolock)
LEFT JOIN
Customer (Nolock) ON o.CustomerID = Customer.ID
INNER JOIN
OrderItem_View (nolock) ON OrderItem_View.OrderID = o.ID
LEFT JOIN
DynamicPrice (nolock) ON OrderItem_View.DynamicPriceID = DynamicPrice.ID
LEFT JOIN
AppointmentTreatment WITH (NOLOCK) ON AppointmentTreatment.ID = OrderItem_View.AppointmentTreatmentID
LEFT JOIN
Employee (NOLOCK) ON Employee.ID = COALESCE(OrderItem_View.EmployeeID, OrderItem_View.Employee2ID, AppointmentTreatment.EmployeeID)
LEFT JOIN
Treatment_View Treatment (nolock) ON Treatment.BillableItemID = OrderItem_View.BillableItemID
LEFT JOIN
ProductVariant (NOLOCK)
LEFT JOIN
Product (NOLOCK) ON Product.ID = ProductVariant.ProductID
ON ProductVariant.BillableItemID = OrderItem_View.BillableItemID
LEFT JOIN
ProductVariant MasterProductVariant (NOLOCK) ON ProductVariant.MasterRecordID = MasterProductVariant.ID
WHERE
o.SpaID = #SpaID
AND o.IsDeleted = 0
AND o.DateCompleted >= CONVERT(DATETIME,0)
AND o.DateCompleted < GetDate()
AND o.StatusID IN (#OrderStatusID_Completed,#OrderStatusID_Shipped)
END
ELSE
SELECT CAST('Insufficient rights.' AS VARCHAR(50)) AS ErrMsg
END
It has to be in the coalesce function. Somewhere between these three - you aren't getting a value
OrderItem_View.EmployeeID
OrderItem_View.Employee2ID
AppointmentTreatment.EmployeeID
So run OrderItem_View by itself and see if there are instances where EmployeeID or Employee2ID is ever null. If so, then try to determine what employees are missing. IF there are employees missing, are they also missing in the AppointmentTreatment table? If so then therein lies the problem.