I'm working with Sql Server, I have written one query.when i'm executing that query getting following error.
Error:
"Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
SELECT b.booking_id,b.booking_ref,b.destination,b.room_format,b.checkin,b.checkout,b.booking_status,b.currency,b.rooms,b.booking_date,
b.adults,b.childs,b.seniors,b.youth,b.child2,b.booking_type,
pb.amount_charged,pb.original_total_cost 'total_amount',b.special_request,b.cancelled_date,b.emergency_contact,b.emergency_email,
(SELECT TOP 2 CAST(isbreakfast AS VARCHAR(10)) + '_' + room_desc FROM tbl_hotel_room_booking WHERE pb.product_booking_id = product_booking_id) 'room_desc',
tba.traveller_address1,tba.traveller_address2,tba.traveller_city,
tba.traveller_state,tba.traveller_country,tba.traveller_zip_code,
th.transaction_amount,th.reversal_amount,th.branch_id,th.agent_id,th.transaction_type,
pb.product_booking_id,pb.product_status,pb.provider_confirmation_code,pb.booking_source,pb.product_name,pb.product_type,pb.product_id,
tft.ticket,
(SELECT TOP 1 as_of_date + '_' + hotel_penalty FROM tbl_hotel_room_cancellation WHERE booking_id='0BCE1ABC-EA42-4030-A9F1-CA8D176825C0') 'as_of_date',
tpd.adult_price,tpd.cost_currency,tpd.sell_currency,tpd.booking_fee,tpd.taxes,tpd.exchange_rate,tpd.subagency_markup_val,
tpd.charged_amount,tpd.child_price,tpd.senior_price,tpd.youth_price, tpd.actual_price,(ISNULL(tpd.markup_total,0) + ISNULL(tpd.subagency_markup_val,0)) 'markup_total', tpd.markup_total 'agency_markup'
FROM tbl_booking b
INNER JOIN tbl_product_booking pb ON b.booking_id = pb.booking_id
LEFT JOIN tbl_transaction_history th ON b.booking_ref = th.reference_number
LEFT JOIN tbl_traveller_billing_address tba ON b.booking_id = tba.booking_id
LEFT JOIN tbl_purchasedproduct_details tpd ON b.booking_id = tpd.booking_id
LEFT JOIN tbl_flight_tickets tft ON b.booking_id = tft.booking_id
WHERE b.booking_id = '0BCE1ABC-EA42-4030-A9F1-CA8D176825C0'
AND (th.transaction_type IS NULL OR LOWER(th.transaction_type) = 'booking' OR LOWER(th.transaction_type) = 'creditcardbooking' OR Lower(th.transaction_type) = 'manualbooking')
Finally i know why i'm getting this error..I'm trying to return multiple result from sub query..
(SELECT TOP 2 CAST(isbreakfast AS VARCHAR(10)) + '_' + room_desc FROM tbl_hotel_room_booking WHERE pb.product_booking_id = product_booking_id) 'room_desc',
can any one help how can i return multiple result here.
If you basically left join your query with that table and set filter for top 2 records i think you will get what you want.
SELECT
b.booking_id,
b.booking_ref,
b.destination,
b.room_format,
b.checkin,
b.checkout,
b.booking_status,
b.currency,
b.rooms,
b.booking_date,
b.adults,
b.childs,
b.seniors,
b.youth,
b.child2,
b.booking_type,
pb.amount_charged,
pb.original_total_cost 'total_amount',
b.special_request,
b.cancelled_date,
b.emergency_contact,
b.emergency_email,
CAST(brb.isbreakfast AS VARCHAR(10)) + '_' + brb.room_desc AS 'room_desc'
tba.traveller_address1,
tba.traveller_address2,
tba.traveller_city,
tba.traveller_state,
tba.traveller_country,
tba.traveller_zip_code,
th.transaction_amount,
th.reversal_amount,
th.branch_id,
th.agent_id,
th.transaction_type,
pb.product_booking_id,
pb.product_status,
pb.provider_confirmation_code,
pb.booking_source,
pb.product_name,
pb.product_type,
pb.product_id,
tft.ticket
(SELECT TOP 1 as_of_date + '_' + hotel_penalty FROM tbl_hotel_room_cancellation WHERE booking_id='0BCE1ABC-EA42-4030-A9F1-CA8D176825C0') 'as_of_date',
tpd.adult_price,tpd.cost_currency,tpd.sell_currency,tpd.booking_fee,tpd.taxes,tpd.exchange_rate,tpd.subagency_markup_val,
tpd.charged_amount,tpd.child_price,tpd.senior_price,tpd.youth_price, tpd.actual_price,(ISNULL(tpd.markup_total,0) + ISNULL(tpd.subagency_markup_val,0)) 'markup_total', tpd.markup_total 'agency_markup'
FROM tbl_booking b
INNER JOIN tbl_product_booking pb ON b.booking_id = pb.booking_id
LEFT JOIN tbl_hotel_room_booking brb ON pb.product_booking_id = brb.product_booking_id
LEFT JOIN tbl_transaction_history th ON b.booking_ref = th.reference_number
LEFT JOIN tbl_traveller_billing_address tba ON b.booking_id = tba.booking_id
LEFT JOIN tbl_purchasedproduct_details tpd ON b.booking_id = tpd.booking_id
LEFT JOIN tbl_flight_tickets tft ON b.booking_id = tft.booking_id
WHERE b.booking_id = '0BCE1ABC-EA42-4030-A9F1-CA8D176825C0'
AND brb.isbreakfast IN (Select Top 2 IsBreakfast
FROM tbl_hotel_room_booking)
AND (th.transaction_type IS NULL
OR LOWER(th.transaction_type) = 'booking'
OR LOWER(th.transaction_type) = 'creditcardbooking' OR Lower(th.transaction_type) = 'manualbooking')
Related
I have this query that is taking a long time to execute. I would like to know how to optimize it. What slows it down are the addition subqueries.
This is the query:
SELECT DISTINCT
dbo.Ventas.IdVenta, dbo.Ventas.CodigoVenta, dbo.Ventas.Fecha_Alta, dbo.M_Operadores.Nombre + ' ' + dbo.M_Operadores.Apellidos AS Operador, SUBSTRING(dbo.Ventas.Cliente, 0, CHARINDEX(CHAR(13), dbo.Ventas.Cliente))
AS Cliente, dbo.M_Centros.Centro,
(SELECT SUM(LineaImporte) AS Expr1
FROM dbo.Ventas_Detalle
WHERE (IdVenta = dbo.Ventas.IdVenta)) - dbo.Ventas.Redondeo AS Importe,
(SELECT ISNULL(SUM(dbo.Movimientos_Caja_Detalle.Ajuste), 0) AS Ajuste
FROM dbo.Movimientos_Caja_Detalle INNER JOIN
dbo.Movimientos_Caja ON dbo.Movimientos_Caja_Detalle.IdMovimientoCaja = dbo.Movimientos_Caja.IdMovimientoCaja
WHERE (dbo.Movimientos_Caja.IdVenta = dbo.Ventas.IdVenta)) AS Ajuste,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_2.Importe), 0) AS Cobrado
FROM dbo.Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_2 INNER JOIN
dbo.Movimientos_Caja AS Movimientos_Caja_2 ON Movimientos_Caja_Detalle_2.IdMovimientoCaja = Movimientos_Caja_2.IdMovimientoCaja
WHERE (Movimientos_Caja_2.IdVenta = dbo.Ventas.IdVenta) OR
(Movimientos_Caja_2.CodigoSobre = dbo.Ventas.CodigoSobre) AND (Movimientos_Caja_2.IdTipoMov_Caja = 7)) AS Cobrado,
(SELECT SUM(LineaImporte) AS Expr1
FROM dbo.Ventas_Detalle AS Ventas_Detalle_1
WHERE (IdVenta = dbo.Ventas.IdVenta)) - dbo.Ventas.Redondeo -
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_1.Importe), 0) AS Cobrado
FROM dbo.Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_1 INNER JOIN
dbo.Movimientos_Caja AS Movimientos_Caja_1 ON Movimientos_Caja_Detalle_1.IdMovimientoCaja = Movimientos_Caja_1.IdMovimientoCaja
WHERE (Movimientos_Caja_1.IdVenta = dbo.Ventas.IdVenta) OR
(Movimientos_Caja_1.CodigoSobre = dbo.Ventas.CodigoSobre) AND (Movimientos_Caja_1.IdTipoMov_Caja = 7)) AS Pendiente,
(SELECT Importe AS expr1
FROM dbo.Vales
WHERE (IdVentaEmision = dbo.Ventas.IdVenta)) AS Vale, dbo.Ventas.CodigoSobre, dbo.Ventas.FechaTerminado, dbo.Ventas.IdCentro_Alta AS IdCentro, dbo.Ventas.FechaEntregado, dbo.Ventas.IdOperador,
dbo.Ventas.FacturaVenta, dbo.Ventas.FechaFactura, dbo.Ventas.EstadoFactura, dbo.Ventas.TipoFactura
FROM dbo.Ventas INNER JOIN
dbo.M_Operadores ON dbo.Ventas.IdOperador = dbo.M_Operadores.IdOperador INNER JOIN
dbo.M_Centros ON dbo.Ventas.IdCentro_Alta = dbo.M_Centros.IdCentro
This is the code after changes based on comments:
SELECT
V.IdVenta, V.CodigoVenta, V.Fecha_Alta, MO.Nombre + ' ' + MO.Apellidos AS Operador, SUBSTRING(V.Cliente, 0, CHARINDEX(CHAR(13), V.Cliente))
AS Cliente, MC.Centro,
(SELECT SUM(LineaImporte) AS Expr1
FROM Ventas_Detalle
WHERE (IdVenta = V.IdVenta)) - V.Redondeo AS Importe,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle.Ajuste), 0) AS Ajuste
FROM Movimientos_Caja_Detalle INNER JOIN
Movimientos_Caja ON Movimientos_Caja_Detalle.IdMovimientoCaja = Movimientos_Caja.IdMovimientoCaja
WHERE (Movimientos_Caja.IdVenta = V.IdVenta)) AS Ajuste,
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_2.Importe), 0) AS Cobrado
FROM Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_2 INNER JOIN
Movimientos_Caja AS Movimientos_Caja_2 ON Movimientos_Caja_Detalle_2.IdMovimientoCaja = Movimientos_Caja_2.IdMovimientoCaja
WHERE (Movimientos_Caja_2.IdVenta = V.IdVenta) OR
(Movimientos_Caja_2.CodigoSobre = V.CodigoSobre) AND (Movimientos_Caja_2.IdTipoMov_Caja = 7)) AS Cobrado,
(SELECT SUM(LineaImporte) AS Expr1
FROM Ventas_Detalle AS Ventas_Detalle_1
WHERE (IdVenta = V.IdVenta)) - V.Redondeo -
(SELECT ISNULL(SUM(Movimientos_Caja_Detalle_1.Importe), 0) AS Cobrado
FROM Movimientos_Caja_Detalle AS Movimientos_Caja_Detalle_1 INNER JOIN
Movimientos_Caja AS Movimientos_Caja_1 ON Movimientos_Caja_Detalle_1.IdMovimientoCaja = Movimientos_Caja_1.IdMovimientoCaja
WHERE (Movimientos_Caja_1.IdVenta = V.IdVenta) OR
(Movimientos_Caja_1.CodigoSobre = V.CodigoSobre) AND (Movimientos_Caja_1.IdTipoMov_Caja = 7)) AS Pendiente,
(SELECT Importe AS expr1
FROM Vales
WHERE (IdVentaEmision = V.IdVenta)) AS Vale, V.CodigoSobre, V.FechaTerminado, V.IdCentro_Alta AS IdCentro, V.FechaEntregado, V.IdOperador,
V.FacturaVenta, V.FechaFactura, V.EstadoFactura, V.TipoFactura
FROM Ventas V INNER JOIN
M_Operadores MO ON V.IdOperador = MO.IdOperador INNER JOIN
M_Centros MC ON V.IdCentro_Alta = MC.IdCentro
my query taking more than 5 minutes to execute can anyone tell me what's wrong in this query, below is the query I try to optimize it but no luck
SELECT DISTINCT
'Freight' AS Expr1000,
'Acknowledged Trip Details' AS detailtype,
sCompanyDesc,
VehicleRegistration.sVehicleRegistrationNumber,
Token.iTokenId,
sTokenNumber,
Token.dtTokenGenerating AS TokenDate,
LoadAssign.sCustomerInvoiceNumber,
dtCustomerInvoiceDate,
FillingPoint.sFillingPointName AS [From],
DecantingPoint.sDecantingPointName AS [To],
CloseLoad.fExpectedFreightAmount AS fExpectedFreightAmount,
ISNULL(PayAdvance.fAdvanceAmount, 0) AS fAdvanceAmount,
CloseLoad.fCommissionAmount AS fCommissionAmount,
CloseLoad.fDecantedQuantity,
0 AS [Shortage Quantity],
0 AS [Shortage Rate],
0 AS [Shortage Amount],
sProductName,
ISNULL((SELECT SUM(ISNULL(JVDetails.fCreditAmount, 0))
FROM Transactions
INNER JOIN JV ON JV.sJVCode = Transactions.sTransactionCode
INNER JOIN JVDetails ON JVDetails.iJVId = JV.iJVId
WHERE CloseLoad.iTokenId = Transactions.iTokenId
AND JV.sDescription = 'Munshiana'),
0) AS Munshiana,
ISNULL(JV.sJVCode, '') + ISNULL(PV.sPVCode, '') AS advdocnum
FROM CloseLoad
INNER JOIN Token ON CloseLoad.iTokenId = Token.iTokenId
INNER JOIN LoadAssign ON CloseLoad.iLoadId = LoadAssign.iLoadId
INNER JOIN FillingPoint ON Token.iFillingPointId = FillingPoint.iFillingPointId
INNER JOIN DecantingPoint ON LoadAssign.iDecantingPointId = DecantingPoint.iDecantingPointId
INNER JOIN Product ON LoadAssign.iProductId = Product.iProductId
INNER JOIN VehicleRegistration ON Token.iVehicleRegistrationId = VehicleRegistration.iVehicleRegistrationId
INNER JOIN Company ON Token.iCompanyId = Company.iCompanyId
LEFT JOIN PayAdvance ON PayAdvance.iTokenId = Token.iTokenId
AND PayAdvance.bIsApproved = 1
LEFT JOIN PV ON PV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND PV.bIsApproved = 1
LEFT JOIN JV ON JV.iPayAdvanceId = PayAdvance.iPayAdvanceId
AND PayAdvance.bIsApproved = 1
AND JV.bIsApproved = 1
WHERE CloseLoad.iLoadId NOT IN (SELECT tfrli.iLoadId
FROM TempFreightReceiptLoadInfo tfrli
INNER JOIN FreightReceiptChqInfo ci ON ci.iFreightReceiptChqInfoId = tfrli.iFreightReceiptChqInfoId
INNER JOIN LoadAssign l1 ON l1.iLoadId = tfrli.iLoadId
WHERE ci.bIsApproved = 1
AND l1.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND tfrli.sAllocationType = 'Freight')
AND LoadAssign.bIsLoadClose = 1
AND Token.iVehicleRegistrationId = 2644
AND LoadAssign.dtCustomerInvoiceDate BETWEEN '8/1/2020' AND '8/30/2020'
AND Token.iCompanyId IN (1, 2, 3)
AND Token.sDecantingPointType IN ('Domestic', 'Export')
AND LoadAssign.bIsActive = 1
AND Token.bIsLoadVerify = 1;
Execute EXPLAIN to find bottleneck.
EXPLAIN SELECT DISTINCT ...
Question:
I get these results (column task_externalId) when I run my query:
TC229090-10000-3
TC229090-20000-3
TC229830-10000-3
TC229685-10000-3
A task (TC229090) can contain multiple rows (10000, 20000), but can also have just one (10000 only).
My full code:
SELECT
v.voorgemeld_handmatig, v.voorgemeld, v.mac, v.orn, v.cdm, v.blo,
v.bco, v.tarcode, (v.timeslotfrom + ' - ' + v.timeslottill),
cast (case
when
(Select ac2.actionSpecificationName
From [COMTECdefault].[dbo].[task] t2
Join [COMTECdefault].[dbo].[actionKind] ak2 On t2.id_actionKind = ak2.id_actionKind
Join [COMTECdefault].[dbo].[actionSpecification] ac2 On ak2.id_actionSpecification = ac2.id_actionSpecification
where t2.task_externalId = (left(t.task_externalId, 15) + '2')) = 'laden'
then 'Vol'
else 'Leeg'
end as text) as IMPORT,
t.task_externalId, a.addressName, a.cityName,
CONVERT(DATE, t.from_date) as [Date],
CONVERT(varchar(8), CONVERT(TIME, t.from_date)) as [Tijd],
res.resourceName, resk.resourceKindName, r.shipOwner,
t.reference,
(Select resourceName
From [COMTECdefault].[dbo].[resource] r5
Left Outer Join [COMTECdefault].[dbo].resourceKind rk5 On rk5.id_resourceKind = r5.id_resourceKind
Where (id_resource = SUBSTRING(pt.StartResources, 0, CHARINDEX(',', pt.StartResources))
or id_resource = PARSENAME(REPLACE(SUBSTRING(pt.StartResources, CHARINDEX(',', pt.StartResources) + 1, LEN(pt.StartResources)), ',', '.'), 4)
or id_resource = PARSENAME(REPLACE(SUBSTRING(pt.StartResources, CHARINDEX(',', pt.StartResources) + 1, LEN(pt.StartResources)), ',', '.'), 3)
or id_resource = PARSENAME(REPLACE(SUBSTRING(pt.StartResources, CHARINDEX(',', pt.StartResources) + 1, LEN(pt.StartResources)), ',', '.'), 2)
or id_resource = PARSENAME(REPLACE(SUBSTRING(pt.StartResources, CHARINDEX(',', pt.StartResources) + 1, LEN(pt.StartResources)), ',', '.'), 1))
and r5.id_resourceKind = 51),
udo.udf_Gewicht, udo.udf_Zegelnummer,
cast (case when a.addressName = 'APM Terminal 2'
then case when udo.udf_Zegelnummer IS NULL
then 0
else 1
end
when a.addressName IN ('ect delta', 'Euromax Terminam C.V.', 'Euromax Terminal')
then case when udo.udf_Gewicht = 0
then 0
else 1
end
else 1
end as bit) as [voormelden],
v.foutcode, v.foutcode_tekst, v.V_door
FROM
[COMTECdefault].[dbo].[task] t
JOIN
[COMTECdefault].[dbo].[actionKind] ak ON t.id_actionKind = ak.id_actionKind
JOIN
[COMTECdefault].[dbo].[actionSpecification] ac ON ak.id_actionSpecification = ac.id_actionSpecification
LEFT OUTER JOIN
[COMTECdefault].[dbo].[resourceOrder] ro ON t.id_order = ro.id_order
LEFT OUTER JOIN
[COMTECdefault].[dbo].[resource] res ON ro.id_resource = res.id_resource
LEFT OUTER JOIN
[COMTECdefault].[dbo].[resourceKind] resk ON res.id_resourceKind= resk.id_resourceKind
LEFT OUTER JOIN
[COMTECdefault].[dbo].[address] a ON t.id_address = a.id_address
LEFT OUTER JOIN
[COMTECdefault].[dbo].[resourceOrder] r ON t.id_order = r.id_order
LEFT OUTER JOIN
[COMTECdefault].[dbo].[order] o ON o.id_order = r.id_order
LEFT OUTER JOIN
[COMTECdefault].[dbo].[voormelden] v ON v.id_task_otd = t.task_externalId
LEFT OUTER JOIN
[COMTECdefault].[dbo].[ud_order] udo ON udo.id_order = t.id_order
LEFT OUTER JOIN
[COMTECdefault].[dbo].[plannedTask] pt on t.id_task = pt.id_task
WHERE
(pt.id_Task IS NULL OR pt.taskstate <> 'finished')
AND (v.canceled IS NULL OR v.canceled = 0)
AND left(res.resourceName, 4) <> 'XXXU'
AND t.canceled = 0
AND (t.from_date <= '2016-11-24 23:59:59')
AND (ac.actionSpecificationName = 'inleveren')
AND a.addressName IN ('APM Terminal 1','APM Terminal 2', 'ect delta', 'rwg', 'Euromax Terminam C.V.', 'Euromax Terminal')
ORDER BY
res.resourceName, a.addressName, t.task_externalId
I only want to show the 20000 task when its exists . Otherwise show the 10000.
Thanks in advance.
I am not going to touch all of that text there may well be was of narrowing down all of the joins etc, but here is the pattern for doing what you want with the task_exteralid column.
DECLARE #Table AS TABLE (task_externalid VARCHAR(100))
INSERT INTO #Table VALUES
('TC229090-10000-3')
,('TC229090-20000-3')
,('TC229830-10000-3')
,('TC229685-10000-3')
;WITH cte AS (
SELECT
*
,RowNumber = ROW_NUMBER() OVER (PARTITION BY
LEFT(task_externalid,CHARINDEX('-',task_externalid) - 1)
ORDER BY task_externalid DESC)
FROM
#Table
)
SELECT *
FROM
cte
WHERE
RowNumber = 1
Create a partitioned ROW_NUMBER on the LEFT most portion of the task_exteralid
Order that by task_exteralid DESC
I have a query with some joins. One of the joins depends of another value.
This is my query:
SELECT *
FROM CLIIRE A
LEFT JOIN CLIIOR B ON A.PTA = B.PTA AND A.ORD = B.ORD AND A.ITE = B.ITE
LEFT JOIN CLIORD C ON C.PTA = B.PTA AND C.ORD = B.ORD
LEFT JOIN CLIPAC D ON C.OPA = D.ORI AND C.PAC = D.PAC
LEFT JOIN CLIREN E ON E.NRE = A.NRE AND D.INS = E.INS AND A.CPT = E.CPT
LEFT JOIN
(SELECT *
FROM CLINOM
WHERE CLA = (CASE WHEN B.PFA = '88882' THEN 'MD' ELSE 'BU' END )) AS N ON B.PFA = N.COD
LEFT JOIN
(SELECT *
FROM CLIMED WHERE PRE = '') AS M ON B.PFA = M.MED
LEFT JOIN CLIPRF P ON B.PRF = P.PRF
WHERE
(D.INS LIKE 'OM%' OR D.INS LIKE 'SOL%')
AND E.NFA IN ('5188')
AND A.CPT IN ('fi', 'pi')
ORDER BY
E.NFA
But I'm getting error in the line:
LEFT JOIN (SELECT * FROM CLINOM WHERE CLA = (CASE WHEN B.PFA = '88882' THEN 'MD' ELSE 'BU' END )) AS N ON B.PFA=N.COD
Looks like SQL Server won't allow me to do that:
The multi-part identifier "B.PFA" could not be bound
The column B.PFA exists.
Can anyone help me? Thanks !
The problem is that the outer query reference is not available in the subquery. Happily, though the subquery is not needed. Try this logic:
LEFT JOIN CLINOM N
ON P.FA = N.COD AND
N.CLA = (CASE WHEN B.PFA = '88882' THEN 'MD' ELSE 'BU' END)
And, you can phrase this without the CASE. Assuming B.PFA is not NULL:
LEFT JOIN CLINOM N
ON P.FA = N.COD AND
((N.CLA = 'MD' AND B.PFA = '88882') OR
(N.CLA = 'BU' AND B.PFA <> '88882')
)
If B.PFA could be NULL:
LEFT JOIN CLINOM N
ON P.FA = N.COD AND
((N.CLA = 'MD' AND B.PFA = '88882') OR
(N.CLA = 'BU' AND (B.PFA <> '88882' OR B.PFS IS NULL))
)
You can also use COALESCE() if you like.
SELECT
*
FROM
RM_Sales_Union
WHERE
DOCDATE >= 'September 1, 2011'
AND DOCDATE < 'October 1, 2011'
AND CUSTNMBR = '2186020'
That query results in an error:
Msg 8134, Level 16, State 1, Line 1
Divide by zero error encountered.
if run as shown.
Excluding the last line AND CUSTNMBR = '2186020' allows the query to complete.
CUSTNMBR is a char(21) field. Divide by zero has me confused.
What is the "correct" way to work around this?
RM_Sales_Union is a union query view:
SELECT ACTNUMBR_1,
ACTNUMBR_2,
ACTNUMBR_3,
ORSLSAMT,
CUSTCLAS,
CUSTNAME,
CUSTNMBR,
SLPRSNID,
DOCABREV,
CSPORNBR,
CURNCYID,
DOCDATE,
DOCNUMBR,
GLPOSTDT,
SLSAMNT,
VOIDSTTS,
SLPRSNFN,
SPRSNSLN,
DocOrigin,
ORFRTAMT,
FRTAMNT,
COMPRCNT,
TRDISAMT,
ORTDISAM,
ORMISCAMT,
ORTAXAMT,
ORCTRXAM
FROM dbo.RM_Sales_Hist
UNION
SELECT ACTNUMBR_1,
ACTNUMBR_2,
ACTNUMBR_3,
ORSLSAMT,
CUSTCLAS,
CUSTNAME,
CUSTNMBR,
SLPRSNID,
DOCABREV,
CSPORNBR,
CURNCYID,
DOCDATE,
DOCNUMBR,
GLPOSTDT,
SLSAMNT,
VOIDSTTS,
SLPRSNFN,
SPRSNSLN,
DocOrigin,
ORFRTAMT,
FRTAMNT,
COMPRCNT,
TRDISAMT,
ORTDISAM,
ORMISCAMT,
ORTAXAMT,
ORCTRXAM
FROM dbo.RM_Sales_Open
RM_Sales_Hist and RM_Sales_Open are views defined as follows:
--RM_Sales_Hist
SELECT dbo.GL_Sales_Accounts.ACTNUMBR_1,
dbo.GL_Sales_Accounts.ACTNUMBR_2,
dbo.GL_Sales_Accounts.ACTNUMBR_3,
ISNULL(dbo.MC020102.ORSLSAMT, dbo.RM30101.SLSAMNT) AS ORSLSAMT,
dbo.RM00101.CUSTCLAS,
dbo.RM00101.CUSTNAME,
dbo.RM00101.CUSTNMBR,
dbo.RM00101.SLPRSNID,
dbo.RM40401.DOCABREV,
dbo.RM30101.CSPORNBR,
dbo.RM30101.CURNCYID,
dbo.RM30101.DOCDATE,
dbo.RM30101.DOCNUMBR,
dbo.RM30101.GLPOSTDT,
dbo.RM30101.SLSAMNT,
dbo.RM30101.VOIDSTTS,
dbo.RM00301.SLPRSNFN,
dbo.RM00301.SPRSNSLN,
'HIST' AS DocOrigin,
ISNULL(dbo.MC020102.ORFRTAMT, dbo.RM30101.FRTAMNT) AS ORFRTAMT,
dbo.RM30101.FRTAMNT,
dbo.RM00301.COMPRCNT,
dbo.RM30101.TRDISAMT,
ISNULL(dbo.MC020102.ORTDISAM, 0) AS ORTDISAM,
ISNULL(dbo.MC020102.ORMISCAMT, 0) AS ORMISCAMT,
ISNULL(dbo.MC020102.ORTAXAMT, 0) AS ORTAXAMT,
ISNULL(dbo.MC020102.ORCTRXAM, 0) AS ORCTRXAM,
dbo.RM00101.STATE
FROM dbo.GL_Sales_Accounts
INNER JOIN dbo.RM30301
ON dbo.GL_Sales_Accounts.DSTINDX = dbo.RM30301.DSTINDX
INNER JOIN dbo.RM30101
ON dbo.RM30301.CUSTNMBR = dbo.RM30101.CUSTNMBR
AND dbo.RM30301.DOCNUMBR = dbo.RM30101.DOCNUMBR
INNER JOIN dbo.RM00101
ON dbo.RM30101.CUSTNMBR = dbo.RM00101.CUSTNMBR
INNER JOIN dbo.RM40401
ON dbo.RM30101.RMDTYPAL = dbo.RM40401.RMDTYPAL
INNER JOIN dbo.RM00301
ON dbo.RM00101.SLPRSNID = dbo.RM00301.SLPRSNID
LEFT OUTER JOIN dbo.MC020102
ON dbo.RM30301.DOCNUMBR = dbo.MC020102.DOCNUMBR
WHERE ( CAST(dbo.RM30301.DOCNUMBR AS VARCHAR(21)) NOT IN (SELECT
CAST(
DOCNUMBR AS
VARCHAR(21)) AS
Expr1
FROM
dbo.Invoices_With_Display_Discounts) )
--RM_Sales_Open
SELECT dbo.GL_Sales_Accounts.ACTNUMBR_1,
dbo.GL_Sales_Accounts.ACTNUMBR_2,
dbo.GL_Sales_Accounts.ACTNUMBR_3,
ISNULL(dbo.MC020102.ORSLSAMT, 0) AS ORSLSAMT,
dbo.RM00101.CUSTCLAS,
dbo.RM00101.CUSTNAME,
dbo.RM00101.CUSTNMBR,
dbo.RM00101.SLPRSNID,
dbo.RM40401.DOCABREV,
dbo.RM20101.CSPORNBR,
dbo.RM20101.CURNCYID,
dbo.RM20101.DOCDATE,
dbo.RM20101.DOCNUMBR,
dbo.RM20101.GLPOSTDT,
dbo.RM20101.SLSAMNT,
dbo.RM20101.VOIDSTTS,
dbo.RM00301.SLPRSNFN,
dbo.RM00301.SPRSNSLN,
'OPEN' AS DocOrigin,
ISNULL(dbo.MC020102.ORFRTAMT, 0) AS ORFRTAMT,
dbo.RM20101.FRTAMNT,
dbo.RM00301.COMPRCNT,
dbo.RM20101.TRDISAMT,
ISNULL(dbo.MC020102.ORTDISAM, 0) AS ORTDISAM,
ISNULL(dbo.MC020102.ORMISCAMT, 0) AS ORMISCAMT,
ISNULL(dbo.MC020102.ORTAXAMT, 0) AS ORTAXAMT,
ISNULL(dbo.MC020102.ORCTRXAM, 0) AS ORCTRXAM,
dbo.RM00101.STATE
FROM dbo.GL_Sales_Accounts
INNER JOIN dbo.RM10101
ON dbo.GL_Sales_Accounts.DSTINDX = dbo.RM10101.DSTINDX
INNER JOIN dbo.RM20101
ON dbo.RM10101.CUSTNMBR = dbo.RM20101.CUSTNMBR
AND dbo.RM10101.DOCNUMBR = dbo.RM20101.DOCNUMBR
INNER JOIN dbo.RM00101
ON dbo.RM20101.CUSTNMBR = dbo.RM00101.CUSTNMBR
INNER JOIN dbo.RM40401
ON dbo.RM20101.RMDTYPAL = dbo.RM40401.RMDTYPAL
INNER JOIN dbo.RM00301
ON dbo.RM00101.SLPRSNID = dbo.RM00301.SLPRSNID
LEFT OUTER JOIN dbo.MC020102
ON dbo.RM10101.DOCNUMBR = dbo.MC020102.DOCNUMBR
WHERE ( CAST(dbo.RM20101.DOCNUMBR AS VARCHAR(21)) NOT IN (SELECT
CAST(
DOCNUMBR AS
varchar(21)) AS
Expr1
FROM
dbo.Invoices_With_Display_Discounts) )
I guess that RM_Sales_Union is a view that contains a division. The filter simply changes something like a COUNT or SUM to give zero, and it is this that is used as divisor
Change it to use something/NULLIF(..., 0) to make the expressions give NULL. Or ISNULL(something/NULLIF(..., 0), 0) to get NULL instead