Arithmetic overflow occurred. when Executing a Stored procedure - sql

Hi There
I have below stored Proc
CREATE PROCEDURE dbo.glextract_branch_audit_figures (#fin_period DATETIME, #runtime VARCHAR(1))
AS
BEGIN
declare #branch INT
declare #debtor_open_balance money
declare #debtor_theo_balance money
declare #debtor_close_balance money
declare #stock_open_balance money
declare #stock_close_balance money
declare #mtd_goods_in money
declare #mtd_goods_out money
declare #mtd_adjustments money
declare #mtd_sales money
declare #stock_theo_balance money
SELECT #branch = branch FROM branch_control
SELECT #debtor_open_balance = debtor_balance, #stock_open_balance = (stock_balance - stock_ind_bf + stock_onrepr_bf) FROM period_control WHERE fin_period = #fin_period
SELECT #debtor_theo_balance = #debtor_open_balance + (SELECT SUM(doc_amt) from cf_debtor_transaction WHERE tran_type IN
(4002, 4004, 4050, 4052, 4099, 4101, 4102, 4103, 4104, 4105, 4106, 4107, 4108, 4109, 4110, 4111, 4112, 4113, 4114, 4115,
4118, 4119, 4123, 4201, 4204, 4211, 4212, 4220, 4225, 4227, 4229, 4232, 4240, 4241, 4243, 4244, 4248, 4249, 4250, 4251, 4275,
4300, 4423, 4502, 4551, 4552, 4599, 4601, 4602, 4603, 4604, 4605, 4606, 4607, 4608, 4609, 4611, 4612, 4613, 4614, 4615, 4616,
4620, 4621, 4702, 4703, 4704, 4705, 4706, 4707, 4708, 4709, 4710, 4711, 4712, 4713, 4713, 4714, 4715, 4716, 4717, 4718, 4719,
4720, 4721, 4722, 4723, 4724, 4725, 4726, 4727, 4728, 4740, 4741, 4742, 4743, 4744, 4750, 4751, 4774, 4777)
AND fin_period = #fin_period)
SELECT #debtor_close_balance = SUM(dbo.cf_acc_balance(account_guid)) FROM account
SELECT #stock_close_balance = SUM((sh.qty_on_hand - sh.qty_on_ind + sh.qty_on_repair) * a.cost) FROM stock_holding sh, all_sku_costs a WHERE a.sku = sh.sku
SELECT #mtd_goods_in = ISNULL(SUM(CASE WHEN tran_type IN (7215, 7225, 7715, 7717, 7718, 7805, 7405, 7705, 7707, 7708) THEN 0 ELSE cost * qty END),0)
FROM stock_transaction
WHERE tran_type IN (7015, 7035, 7045, 7105, 7115, 7125, 7185, 7135, 7145, 7155, 7205, 7215, 7225, 7235,
7245, 7255, 7265, 7275, 7285, 7295, 7405, 7415, 7445, 7455, 7465, 7475, 7485, 7495,
3502, 4599, 7955, 7305, 7335, 7175, 7195)
AND fin_period = #fin_period
SELECT #mtd_goods_out = ISNULL(SUM(CASE WHEN tran_type IN (7215, 7225, 7715, 7717, 7718, 7805, 7405, 7705, 7707, 7708) THEN 0 ELSE (cost * qty) * -1 END),0)
FROM stock_transaction
WHERE tran_type IN (7505, 7515, 7535, 7605, 7615, 7625, 7685, 7635, 7645, 7655, 7665, 7705, 7715, 7725,
7735, 7745, 7755, 7765, 7795, 7805, 7815, 7845, 7855, 7865, 7885, 7895, 7875, 7925,
3001, 3002, 4099, 7956, 7775, 7935, 7675, 7695)
AND fin_period = #fin_period
SELECT #mtd_adjustments = ISNULL(SUM(CASE WHEN tran_type IN (7717,7718,7707,7708) THEN 0
ELSE CASE WHEN tran_type IN (7018,7048,7718,7829,7868) THEN (cost * qty) * -1
ELSE (cost * qty) END END),0)
FROM stock_transaction
WHERE tran_type in (7017, 7018, 7037, 7038, 7047, 7048, 7107, 7108, 7117, 7118, 7127, 7128, 7137, 7138,
7147, 7148, 7207, 7208, 7217, 7218, 7227, 7228, 7427, 7437, 7447, 7448, 7497, 7507,
7508, 7517, 7518, 7537, 7538, 7647, 7648, 7707, 7708, 7717, 7718, 7828, 7838, 7868,
7898, 7438, 7417, 7818, 7957, 7958, 7967, 7968, 7428, 7438, 7829, 7839)
AND fin_period = #fin_period
SELECT #mtd_sales = ISNULL(SUM(cost * -1),0) FROM debtor_transaction WHERE tran_type IN (4002,4502) AND fin_period = #fin_period
SELECT #stock_theo_balance = #stock_open_balance + #mtd_goods_in + #mtd_goods_out + #mtd_adjustments + #mtd_sales
IF (#runtime = 'E')
BEGIN
TRUNCATE TABLE GL_WK_BRANCH_AUDIT_FIGURES
INSERT INTO GL_WK_BRANCH_AUDIT_FIGURES
SELECT
#fin_period as Period,
#branch as BranchCode,
ISNULL(#debtor_open_balance,0) as DebtorsOpening,
ISNULL(#debtor_close_balance,0) as DebtorsClosing,
ISNULL(#stock_open_balance,0) as StockOpening,
ISNULL(#stock_close_balance,0) as StockClosing,
ISNULL(#debtor_theo_balance,0) - ISNULL(#debtor_close_balance,0) as DebtorsDiff,
ISNULL(#stock_theo_balance,0) - ISNULL(#stock_close_balance,0) as StockDiff
END
ELSE
BEGIN
TRUNCATE TABLE GL_BRANCH_AUDIT_FIGURES
INSERT INTO GL_BRANCH_AUDIT_FIGURES
SELECT
#fin_period as Period,
#branch as BranchCode,
ISNULL(#debtor_open_balance,0) as DebtorsOpening,
ISNULL(#debtor_close_balance,0) as DebtorsClosing,
ISNULL(#stock_open_balance,0) as StockOpening,
ISNULL(#stock_close_balance,0) as StockClosing,
ISNULL(#debtor_theo_balance,0) - ISNULL(#debtor_close_balance,0) as DebtorsDiff,
ISNULL(#stock_theo_balance,0) - ISNULL(#stock_close_balance,0) as StockDiff
END
END
I tried to execute the proc as shown below, passing the fin period and runtime parameter
execute dbo.glextract_branch_audit_figures'2018-08-05', 'E'
However, it is giving me the: Arithmetic overflow occurred error
I have a stock transaction_table that has a field called doc_amt with a big amount.
if I change this amount to something smaller it doesn't crash with the above error.
Please see the value on stock_transaction below:
refer on the procedure above
SELECT #mtd_goods_out

The maximum size of a money datatype is listed here - if you breach that size you will get an artithmetic overflow. Your only alternative is to use a specific numeric datatype instead which allows larger sizes:
http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc36271.1600/doc/html/san1393050391020.html

Related

Microsoft SQL query to view

I have this complex query that i want to turn into a view.
This query comes from https://snippets.cacher.io/snippet/3e84b01b7d52b4ca7807 and i want to save it in a view or even as a table if possible.
`
/*##=============================================*/
/*## QUERY BODY */
/*##=============================================*/
/* #region QueryBody */
/* Testing variables !! Need to be commented for Production !! */
-- DECLARE #UserSIDs AS NVARCHAR(10) = 'Disabled';
-- DECLARE #CollectionID AS NVARCHAR(10) = 'SMS00001';
-- DECLARE #Locale AS INT = 2;
-- DECLARE #Categories AS NVARCHAR(250) = 'Tools';
-- DECLARE #Compliant AS INT = 0;
-- DECLARE #Targeted AS INT = 1;
-- DECLARE #Superseded AS INT = 0;
-- DECLARE #ArticleID AS NVARCHAR(10) = '';
-- DECLARE #ExcludeArticleIDs AS NVARCHAR(250) = '';
/* Variable declaration */
DECLARE #LCID AS INT = dbo.fn_LShortNameToLCID(#Locale);
DECLARE #HelperFunctionExists AS INT = 0;
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* Check for helper function */
IF OBJECT_ID('[dbo].[ufn_CM_GetNextMaintenanceWindow]') IS NOT NULL
SET #HelperFunctionExists = 1;
/* Initialize HealthState descriptor table */
DECLARE #HealthState TABLE (
BitMask INT
, StateName NVARCHAR(250)
)
/* Populate HealthState table */
INSERT INTO #HealthState (BitMask, StateName)
VALUES
('0', 'Healthy')
, ('1', 'Unmanaged')
, ('2', 'Inactive')
, ('4', 'Health Evaluation Failed')
, ('8', 'Pending Restart')
, ('16', 'Update Scan Failed')
, ('32', 'Update Scan Late')
, ('64', 'No Maintenance Window')
, ('128', 'Distant Maintenance Window')
, ('256', 'Expired Maintenance Window')
/* Initialize ClientState descriptor table */
DECLARE #ClientState TABLE (
BitMask INT
, StateName NVARCHAR(100)
)
/* Populate ClientState table */
INSERT INTO #ClientState (BitMask, StateName)
VALUES
('0', 'No Reboot')
, ('1', 'Configuration Manager')
, ('2', 'File Rename')
, ('4', 'Windows Update')
, ('8', 'Add or Remove Feature')
CREATE TABLE #MaintenanceInfo (
ResourceID INT
, NextServiceWindow DATETIME
)
/* Get maintenance data */
IF #HelperFunctionExists = 1
BEGIN
WITH Maintenance_CTE AS (
SELECT
CollectionMembers.ResourceID
, NextServiceWindow.Duration
, NextServiceWindow.NextServiceWindow
, RowNumber = DENSE_RANK() OVER (PARTITION BY ResourceID ORDER BY NextServiceWindow.NextServiceWindow)
, ServiceWindowType
, ServiceWindow.Enabled
FROM vSMS_ServiceWindow AS ServiceWindow
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.CollectionID = ServiceWindow.SiteID
JOIN fn_rbac_Collection(#UserSIDs) AS Collections ON Collections.CollectionID = CollectionMembers.CollectionID
AND Collections.CollectionType = 2 -- Device Collections
CROSS APPLY ufn_CM_GetNextMaintenanceWindow(ServiceWindow.Schedules, ServiceWindow.RecurrenceType) AS NextServiceWindow
WHERE NextServiceWindow.NextServiceWindow IS NOT NULL
AND ServiceWindowType <> 5 -- OSD Service
)
/* Populate MaintenanceInfo table and remove duplicates */
INSERT INTO #MaintenanceInfo(ResourceID, NextServiceWindow)
SELECT
ResourceID
, NextServiceWindow
FROM Maintenance_CTE
WHERE RowNumber = 1
END
/* Get update data */
;
WITH UpdateInfo_CTE
AS (
SELECT
ResourceID = Systems.ResourceID
, Missing = COUNT(*)
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_UpdateComplianceStatus(#UserSIDs) AS ComplianceStatus ON ComplianceStatus.ResourceID = Systems.ResourceID
AND ComplianceStatus.Status = 2 -- Filter on 'Required' (0 = Unknown, 1 = NotRequired, 2 = Required, 3 = Installed)
JOIN fn_rbac_ClientCollectionMembers(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = ComplianceStatus.ResourceID
JOIN fn_rbac_UpdateInfo(#LCID, #UserSIDs) AS UpdateCIs ON UpdateCIs.CI_ID = ComplianceStatus.CI_ID
AND UpdateCIs.IsSuperseded IN (#Superseded)
AND UpdateCIs.CIType_ID IN (1, 8) -- Filter on 1 Software Updates, 8 Software Update Bundle (v_CITypes)
AND UpdateCIs.ArticleID NOT IN ( -- Filter on ArticleID csv list
SELECT VALUE FROM STRING_SPLIT(#ExcludeArticleIDs, ',')
)
AND UpdateCIs.Title NOT LIKE ( -- Filter Preview updates
'[1-9][0-9][0-9][0-9]-[0-9][0-9]_Preview_of_%'
)
JOIN fn_rbac_CICategoryInfo_All(#LCID, #UserSIDs) AS CICategory ON CICategory.CI_ID = ComplianceStatus.CI_ID
AND CICategory.CategoryTypeName = 'UpdateClassification'
AND CICategory.CategoryInstanceName IN (#Categories) -- Filter on Selected Update Classification Categories
LEFT JOIN fn_rbac_CITargetedMachines(#UserSIDs) AS Targeted ON Targeted.ResourceID = ComplianceStatus.ResourceID
AND Targeted.CI_ID = ComplianceStatus.CI_ID
WHERE CollectionMembers.CollectionID = #CollectionID
AND IIF(Targeted.ResourceID IS NULL, 0, 1) IN (#Targeted) -- Filter on 'Targeted' or 'NotTargeted'
AND IIF(UpdateCIs.ArticleID = #ArticleID, 1, 0) = IIF(#ArticleID <> '', 1, 0)
GROUP BY
Systems.ResourceID
)
/* Get device info */
SELECT
Systems.ResourceID
/* Set Health states. You can find the coresponding values in the HealthState table above */
, HealthStates = (
IIF(CombinedResources.IsClient != 1, POWER(1, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Inactive/Pass'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Unknown'
, POWER(2, 1), 0)
+
IIF(
ClientSummary.ClientStateDescription = 'Active/Fail'
OR
ClientSummary.ClientStateDescription = 'Inactive/Fail'
, POWER(4, 1), 0
)
+
IIF(CombinedResources.ClientState != 0, POWER(8, 1), 0)
+
IIF(UpdateScan.LastErrorCode != 0, POWER(16, 1), 0)
+
IIF(UpdateScan.LastScanTime < (SELECT DATEADD(dd, -14, CURRENT_TIMESTAMP)), POWER(32, 1), 0)
+
IIF(ISNULL(NextServiceWindow, 0) = 0 AND #HelperFunctionExists = 1, POWER(64, 1), 0)
+
IIF(NextServiceWindow > (SELECT DATEADD(dd, 30, CURRENT_TIMESTAMP)), POWER(128, 1), 0)
+
IIF(NextServiceWindow < (CURRENT_TIMESTAMP), POWER(256, 1), 0)
)
, Missing = ISNULL(Missing, (IIF(CombinedResources.IsClient = 1, 0, NULL)))
, Device = (
IIF(
SystemNames.Resource_Names0 IS NOT NULL, UPPER(SystemNames.Resource_Names0)
, IIF(Systems.Full_Domain_Name0 IS NOT NULL, Systems.Name0 + '.' + Systems.Full_Domain_Name0, Systems.Name0)
)
)
, OperatingSystem = (
CASE
WHEN OperatingSystem.Caption0 != '' THEN
CONCAT(
REPLACE(OperatingSystem.Caption0, 'Microsoft ', ''), -- Remove 'Microsoft ' from OperatingSystem
REPLACE(OperatingSystem.CSDVersion0, 'Service Pack ', ' SP') -- Replace 'Service Pack ' with ' SP' in OperatingSystem
)
ELSE (
/* Workaround for systems not in GS_OPERATING_SYSTEM table */
CASE
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.1%' THEN 'Windows 7'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.2%' THEN 'Windows 8'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 6.3%' THEN 'Windows 8.1'
WHEN CombinedResources.DeviceOS LIKE '%Workstation 10.0%' THEN 'Windows 10'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.0' THEN 'Windows Server 2008'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.1' THEN 'Windows Server 2008R2'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.2' THEN 'Windows Server 2012'
WHEN CombinedResources.DeviceOS LIKE '%Server 6.3' THEN 'Windows Server 2012 R2'
WHEN Systems.Operating_System_Name_And0 LIKE '%Server 10%' THEN (
CASE
WHEN CAST(REPLACE(Build01, '.', '') AS INTEGER) > 10017763 THEN 'Windows Server 2019'
ELSE 'Windows Server 2016'
END
)
ELSE Systems.Operating_System_Name_And0
END
)
END
)
, LastBootTime = (
CONVERT(NVARCHAR(16), OperatingSystem.LastBootUpTime0, 120)
)
, PendingRestart = (
CASE
WHEN CombinedResources.IsClient = 0
OR CombinedResources.ClientState = 0
THEN NULL
ELSE (
STUFF(
REPLACE(
(
SELECT '#!' + LTRIM(RTRIM(StateName)) AS [data()]
FROM #ClientState
WHERE BitMask & CombinedResources.ClientState <> 0
FOR XML PATH('')
),
' #!',', '
),
1, 2, ''
)
)
END
)
, ClientState = (
CASE CombinedResources.IsClient
WHEN 1 THEN ClientSummary.ClientStateDescription
ELSE 'Unmanaged'
END
)
, ClientVersion = CombinedResources.ClientVersion
, LastUpdateScan = (
CONVERT(NVARCHAR(16), UpdateScan.LastScanTime, 120)
)
, LastScanLocation = NULLIF(UpdateScan.LastScanPackageLocation, '')
, LastScanError = NULLIF(UpdateScan.LastErrorCode, 0)
, NextServiceWindow = IIF(CombinedResources.IsClient != 1, NULL, CONVERT(NVARCHAR(16), NextServiceWindow, 120))
FROM fn_rbac_R_System(#UserSIDs) AS Systems
JOIN fn_rbac_CombinedDeviceResources(#UserSIDs) AS CombinedResources ON CombinedResources.MachineID = Systems.ResourceID
LEFT JOIN fn_rbac_RA_System_ResourceNames(#UserSIDs) AS SystemNames ON SystemNames.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_GS_OPERATING_SYSTEM(#UserSIDs) AS OperatingSystem ON OperatingSystem.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_CH_ClientSummary(#UserSIDs) AS ClientSummary ON ClientSummary.ResourceID = Systems.ResourceID
LEFT JOIN fn_rbac_UpdateScanStatus(#UserSIDs) AS UpdateScan ON UpdateScan.ResourceID = Systems.ResourceID
LEFT JOIN #MaintenanceInfo AS Maintenance ON Maintenance.ResourceID = Systems.ResourceID
LEFT JOIN UpdateInfo_CTE AS UpdateInfo ON UpdateInfo.ResourceID = Systems.ResourceID
JOIN fn_rbac_FullCollectionMembership(#UserSIDs) AS CollectionMembers ON CollectionMembers.ResourceID = Systems.ResourceID
WHERE CollectionMembers.CollectionID = #CollectionID
AND (
CASE -- Compliant (0 = No, 1 = Yes, 2 = Unknown)
WHEN Missing = 0 OR (Missing IS NULL AND Systems.Client0 = 1) THEN 1 -- Yes
WHEN Missing > 0 AND Missing IS NOT NULL THEN 0 -- No
ELSE 2 -- Unknown
END
) IN (#Compliant)
/* Perform cleanup */
IF OBJECT_ID('tempdb..#MaintenanceInfo', 'U') IS NOT NULL
DROP TABLE #MaintenanceInfo;
/* #endregion */
/*##=============================================*/
/*## END QUERY BODY */
/*##=============================================*/
`
Is there an easy way to achieve this?
I have tried to look at the official Microsoft documentation but are still not able to convert the query to a view. https://learn.microsoft.com/en-us/sql/t-sql/statements/create-view-transact-sql?view=sql-server-ver16
As I am new to SQL language I am not sure where to start.
So I agree with Larnu, that this probably doesn't make a ton of sense. But there are cases where one might want to be able to run multiple batches of queries / procedural code from an object that's as consumable as a view. I've done this once in a case where I needed to maximize my options for performance tuning without losing the consumability of the object. So for the sake of when it does make sense, this is something you could do:
Wrap your code in a stored procedure.
Use OPENQUERY() to call your procedure.
Wrap the OPENQUERY() call in a view.
Limitations with this methodology is it's rather static:
You can't pass parameters to your stored procedure
If you use temp tables in your stored procedure, then you need to use the WITH RESULT SETS clause to explicitly define the shape of your result set
The procedure can only return one result set
The SQL Server Engine puts a hard-coded cardinality estimate of 10,000 against OPENQUERY(). So in cases where your procedure returns a lot more rows (typically an order of magnitude or more) than 10,000, e.g. 1 million rows, then you may experience some performance issues with joining the wrapper view to other objects.
Example:
-- Step 1: Wrap the procedural code in a stored procedure
CREATE PROCEDURE dbo.RunSomeCode
AS
BEGIN
CREATE TABLE #Results (ID INT, SomeValue VARCHAR(100));
DECLARE #SomeVariable INT = 0;
WHILE (#SomeVariable < 5)
BEGIN
SET #SomeVariable = #SomeVariable + 1;
INSERT INTO #Results (ID, SomeValue)
SELECT ID, SomeValue
FROM SomeTable
WHERE ID = #SomeVariable
END
SELECT ID, SomeValue
FROM #Results;
END
GO
-- Step 2 & 3: Wrap an OPENQUERY() call to the procedure in a view.
CREATE VIEW dbo.SomeView
AS
SELECT ID, SomeValue
FROM OPENQUERY
(
'
LocalServerName,
EXEC dbo.RunSomeCode
WITH RESULT SETS
((
ID INT,
SomeValue VARCHAR(100)
))
'
);
Voila, you can now execute the procedure by SELECTing from the view:
SELECT ID, SomeValue
FROM dbo.SomeView;

Stored procedue issue with AND statement when checking is null

I can't work out why my value is being ignored.
In my stored procedure it has these two AND statements
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#Printed IS NULL OR o.[Printed] = #Printed)
The #Printed value is a bit same as #Current, and is passed through to the stored procedure just the same as #Current
But the printed value doesn't pull results, it's like it's doing nothing although I know the results should vary.
I'm converting a linq query to the stored procedure, so I know the results should differ.
Here is the part of the linq query which is used.
if (current.HasValue && current.Value)
query = query.Where(o => o.OrderStatusId != (int)OrderStatus.Cancelled && o.OrderStatusId != (int)OrderStatus.Complete && !((o.ShippingStatusId == (int)ShippingStatus.Shipped || o.ShippingStatusId == (int)ShippingStatus.Delivered) && o.Printed && (o.PaymentStatusId == (int)PaymentStatus.Paid || o.PaymentStatusId == (int)PaymentStatus.PartiallyRefunded || o.PaymentStatusId == (int)PaymentStatus.Refunded)));
if (printed.HasValue)
query = query.Where(o => printed.Value == o.Printed);
Any ideas
UPDATE:
Looking at the query from linq in vs debugger I can see the following query, but I' no db expert so I'm a little lost looking at this one.
{SELECT
[Project2].[Id] AS [Id],
[Project2].[OrderGuid] AS [OrderGuid],
[Project2].[StoreId] AS [StoreId],
[Project2].[CustomerId] AS [CustomerId],
[Project2].[BillingAddressId] AS [BillingAddressId],
[Project2].[ShippingAddressId] AS [ShippingAddressId],
[Project2].[PickUpInStore] AS [PickUpInStore],
[Project2].[OrderStatusId] AS [OrderStatusId],
[Project2].[ShippingStatusId] AS [ShippingStatusId],
[Project2].[PaymentStatusId] AS [PaymentStatusId],
[Project2].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Project2].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Project2].[CurrencyRate] AS [CurrencyRate],
[Project2].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Project2].[VatNumber] AS [VatNumber],
[Project2].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Project2].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Project2].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Project2].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Project2].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Project2].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Project2].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Project2].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Project2].[TaxRates] AS [TaxRates],
[Project2].[OrderTax] AS [OrderTax],
[Project2].[OrderDiscount] AS [OrderDiscount],
[Project2].[OrderTotal] AS [OrderTotal],
[Project2].[RefundedAmount] AS [RefundedAmount],
[Project2].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Project2].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Project2].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Project2].[CustomerLanguageId] AS [CustomerLanguageId],
[Project2].[AffiliateId] AS [AffiliateId],
[Project2].[CustomerIp] AS [CustomerIp],
[Project2].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Project2].[CardType] AS [CardType],
[Project2].[CardName] AS [CardName],
[Project2].[CardNumber] AS [CardNumber],
[Project2].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Project2].[CardCvv2] AS [CardCvv2],
[Project2].[CardExpirationMonth] AS [CardExpirationMonth],
[Project2].[CardExpirationYear] AS [CardExpirationYear],
[Project2].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Project2].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Project2].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Project2].[CaptureTransactionId] AS [CaptureTransactionId],
[Project2].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Project2].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Project2].[PaidDateUtc] AS [PaidDateUtc],
[Project2].[ShippingMethod] AS [ShippingMethod],
[Project2].[Printed] AS [Printed],
[Project2].[PrintedOnUtc] AS [PrintedOnUtc],
[Project2].[IsSupport] AS [IsSupport],
[Project2].[EditedStatusId] AS [EditedStatusId],
[Project2].[Deleted] AS [Deleted],
[Project2].[Id1] AS [Id1]
FROM ( SELECT
CASE WHEN (([Extent1].[Printed] <> 1) AND (N'Express Delivery' = [Extent1].[ShippingMethod])) THEN N'1' ELSE N'0' END AS [C1],
CASE WHEN ([Extent1].[Printed] <> 1) THEN CASE WHEN (([Extent1].[ShippingMethod] IN (N'Fast Delivery',N'My Point Pickup')) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[GenericAttribute] AS [Extent3]
WHERE (N'WarehouseOverride' = [Extent3].[Key]) AND (N'Order' = [Extent3].[KeyGroup]) AND ([Extent3].[EntityId] = [Extent1].[Id])
))) THEN N'0' ELSE N'1' END ELSE N'0' END AS [C2],
[Extent1].[Id] AS [Id],
[Extent1].[OrderGuid] AS [OrderGuid],
[Extent1].[StoreId] AS [StoreId],
[Extent1].[CustomerId] AS [CustomerId],
[Extent1].[BillingAddressId] AS [BillingAddressId],
[Extent1].[ShippingAddressId] AS [ShippingAddressId],
[Extent1].[PickUpInStore] AS [PickUpInStore],
[Extent1].[OrderStatusId] AS [OrderStatusId],
[Extent1].[ShippingStatusId] AS [ShippingStatusId],
[Extent1].[PaymentStatusId] AS [PaymentStatusId],
[Extent1].[PaymentMethodSystemName] AS [PaymentMethodSystemName],
[Extent1].[CustomerCurrencyCode] AS [CustomerCurrencyCode],
[Extent1].[CurrencyRate] AS [CurrencyRate],
[Extent1].[CustomerTaxDisplayTypeId] AS [CustomerTaxDisplayTypeId],
[Extent1].[VatNumber] AS [VatNumber],
[Extent1].[OrderSubtotalInclTax] AS [OrderSubtotalInclTax],
[Extent1].[OrderSubtotalExclTax] AS [OrderSubtotalExclTax],
[Extent1].[OrderSubTotalDiscountInclTax] AS [OrderSubTotalDiscountInclTax],
[Extent1].[OrderSubTotalDiscountExclTax] AS [OrderSubTotalDiscountExclTax],
[Extent1].[OrderShippingInclTax] AS [OrderShippingInclTax],
[Extent1].[OrderShippingExclTax] AS [OrderShippingExclTax],
[Extent1].[PaymentMethodAdditionalFeeInclTax] AS [PaymentMethodAdditionalFeeInclTax],
[Extent1].[PaymentMethodAdditionalFeeExclTax] AS [PaymentMethodAdditionalFeeExclTax],
[Extent1].[TaxRates] AS [TaxRates],
[Extent1].[OrderTax] AS [OrderTax],
[Extent1].[OrderDiscount] AS [OrderDiscount],
[Extent1].[OrderTotal] AS [OrderTotal],
[Extent1].[RefundedAmount] AS [RefundedAmount],
[Extent1].[RewardPointsWereAdded] AS [RewardPointsWereAdded],
[Extent1].[CheckoutAttributeDescription] AS [CheckoutAttributeDescription],
[Extent1].[CheckoutAttributesXml] AS [CheckoutAttributesXml],
[Extent1].[CustomerLanguageId] AS [CustomerLanguageId],
[Extent1].[AffiliateId] AS [AffiliateId],
[Extent1].[CustomerIp] AS [CustomerIp],
[Extent1].[AllowStoringCreditCardNumber] AS [AllowStoringCreditCardNumber],
[Extent1].[CardType] AS [CardType],
[Extent1].[CardName] AS [CardName],
[Extent1].[CardNumber] AS [CardNumber],
[Extent1].[MaskedCreditCardNumber] AS [MaskedCreditCardNumber],
[Extent1].[CardCvv2] AS [CardCvv2],
[Extent1].[CardExpirationMonth] AS [CardExpirationMonth],
[Extent1].[CardExpirationYear] AS [CardExpirationYear],
[Extent1].[AuthorizationTransactionId] AS [AuthorizationTransactionId],
[Extent1].[AuthorizationTransactionCode] AS [AuthorizationTransactionCode],
[Extent1].[AuthorizationTransactionResult] AS [AuthorizationTransactionResult],
[Extent1].[CaptureTransactionId] AS [CaptureTransactionId],
[Extent1].[CaptureTransactionResult] AS [CaptureTransactionResult],
[Extent1].[SubscriptionTransactionId] AS [SubscriptionTransactionId],
[Extent1].[PaidDateUtc] AS [PaidDateUtc],
[Extent1].[ShippingMethod] AS [ShippingMethod],
[Extent1].[Printed] AS [Printed],
[Extent1].[PrintedOnUtc] AS [PrintedOnUtc],
[Extent1].[IsSupport] AS [IsSupport],
[Extent1].[EditedStatusId] AS [EditedStatusId],
[Extent1].[Deleted] AS [Deleted],
[Extent2].[Id] AS [Id1]
FROM [dbo].[Order] AS [Extent1]
LEFT OUTER JOIN [dbo].[RewardPointsHistory] AS [Extent2] ON ([Extent2].[UsedWithOrder_Id] IS NOT NULL) AND ([Extent1].[Id] = [Extent2].[UsedWithOrder_Id])
WHERE ([Extent1].[Deleted] <> 1) AND (40 <> [Extent1].[OrderStatusId]) AND (30 <> [Extent1].[OrderStatusId]) AND ( NOT (([Extent1].[ShippingStatusId] IN (30,40)) AND ([Extent1].[Printed] = 1) AND ([Extent1].[PaymentStatusId] IN (30,35,40))))
) AS [Project2]
ORDER BY [Project2].[C1] DESC, [Project2].[Printed] ASC, [Project2].[C2] DESC, [Project2].[CreatedOnUtc] DESC}
Here is my stored procedure for you to look at:
USE [Test]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[OrderLoad]
-- Add the parameters for the stored procedure here
#OrderId int = null,
#CustomerId int = null,
#WarehouseId int = null,
#BillingCountryId int = null,
#PaymentMethodSystemName nvarchar(max) = null,
#OrderStatusId int = null,
#PaymentStatusId int = null,
#ShippingStatusId int = null,
#BillingEmail nvarchar(max) = null,
#BillingFirstName nvarchar(max) = null,
#BillingLastName nvarchar(max) = null,
#PurchasedPreviously bit = null,
#Printed bit = null,
#OrderNotes nvarchar(max) = null,
#ZendeskId nvarchar(max) = null,
#RexCode nvarchar(max) = null,
#Current bit = null,
#Challenge bit = null,
#ShippingMethod nvarchar(max) = null,
#EditedStatus int = null,
#OrderGuid nvarchar(max) = null,
#SupportReason int = null,
#CreatedFromUtc datetime = null,
#CreatedToUtc datetime = null,
#IsSupport bit = null,
#PageIndex int = 0,
#PageSize int = 2147483644,
#TotalRecords int = null OUTPUT
AS
BEGIN
DECLARE
#sql nvarchar(max)
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
create table #TempTotal (RowNum int identity(1,1), id int);
--select all
INSERT INTO #TempTotal ([id])
SELECT o.[Id]
FROM [Test].[dbo].[Order] o with (NOLOCK)
-- Another alternative to bypass left join, which works with pagination
LEFT join [Test].[dbo].[Address] a on a.Id = o.BillingAddressId and (
coalesce(#BillingEmail,'') <> ''
or coalesce(#BillingFirstName,'') <> ''
or coalesce(#BillingLastName,'') <> ''
or coalesce(#BillingCountryId,'') <> ''
)
WHERE
o.[Deleted] = 0
/*AND (#BillingEmail IS null OR a.[Email] LIKE '%' + #BillingEmail + '%')
AND (#BillingFirstName IS null OR a.[FirstName] LIKE '%' + #BillingFirstName + '%')
AND (#BillingLastName IS null OR a.[LastName] LIKE '%' + #BillingLastName + '%')
AND (#BillingCountryId IS null OR a.[CountryId] = #BillingCountryId)
*/
AND (#Printed IS NULL OR o.[Printed] = #Printed)
AND (#Current IS NULL OR (o.[OrderStatusId] <> 40) AND (o.[OrderStatusId] <> 30) AND ( NOT ((o.[ShippingStatusId] IN (30, 40)) /*AND (o.[Printed] = '1')*/ AND (o.[PaymentStatusId] IN (30, 35, 40)))))
AND (#IsSupport IS null OR o.[IsSupport] = #IsSupport)
--paging
DECLARE #PageLowerBound int
SET #PageLowerBound = #PageSize * #PageIndex
-- Return the paged records
select [Id] --note select * can produce unexpected results
,[OrderGuid]
,[RexOrderId]
,[StoreId]
,[CustomerId]
,[BillingAddressId]
,[ShippingAddressId]
,[PickUpInStore]
,[OrderStatusId]
,[ShippingStatusId]
,[PaymentStatusId]
,[PaymentMethodSystemName]
,[CustomerCurrencyCode]
,[CurrencyRate]
,[CustomerTaxDisplayTypeId]
,[VatNumber]
,[OrderSubtotalInclTax]
,[OrderSubtotalExclTax]
,[OrderSubTotalDiscountInclTax]
,[OrderSubTotalDiscountExclTax]
,[OrderShippingInclTax]
,[OrderShippingExclTax]
,[PaymentMethodAdditionalFeeInclTax]
,[PaymentMethodAdditionalFeeExclTax]
,[TaxRates]
,[OrderTax]
,[OrderDiscount]
,[OrderTotal]
,[RefundedAmount]
,[RewardPointsWereAdded]
,[CheckoutAttributeDescription]
,[CheckoutAttributesXml]
,[CustomerLanguageId]
,[AffiliateId]
,[CustomerIp]
,[AllowStoringCreditCardNumber]
,[CardType]
,[CardName]
,[CardNumber]
,[MaskedCreditCardNumber]
,[CardCvv2]
,[CardExpirationMonth]
,[CardExpirationYear]
,[AuthorizationTransactionId]
,[AuthorizationTransactionCode]
,[AuthorizationTransactionResult]
,[CaptureTransactionId]
,[CaptureTransactionResult]
,[SubscriptionTransactionId]
,[PaidDateUtc]
,[ShippingMethod]
,[Printed]
,[Deleted]
,[CreatedOnUtc]
,[EditedStatusId]
,[IsSupport]
,[PrintedOnUtc]
from [Test].[dbo].[Order] ord with (NOLOCK)
where ord.[Id] in (
select id
from #TempTotal tt
)
ORDER BY
(CASE #IsSupport
WHEN 0 THEN ord.[Printed]
END) ASC
, (CASE #IsSupport
WHEN 0 THEN ord.[CreatedOnUtc]
END) DESC
, (CASE #IsSupport
WHEN 1 THEN ord.[CreatedOnUtc]
END) DESC
--ORDER BY ord.[CreatedOnUtc] DESC
OFFSET #PageLowerBound ROWS FETCH NEXT #PageSize ROWS ONLY;
--total records
select #TotalRecords = count(*) from #TempTotal;
DROP TABLE #TempTotal
END

How to query Oracle grouping?

I have such a problem and I don't know how to solve it, can you help me? t
The query returns a result that is shown on the photo and I want to get it to be shown in one line instead of many based on type of age.
https://imgur.com/a/OA6CBpa
with x as (
select ai.invoice_id, ai.invoice_num, ai.invoice_amount, ai.amount_paid,
trial.entity_id, trial.acctd_amount, trial.entered_amount, trial.gl_date,
aps.amount_remaining, aps.gross_amount, aps.due_date, aps.payment_status_flag,
trial.gl_date - aps.due_date dni_opoznienia
from ap_invoices_all ai,
xla.xla_transaction_entities xte,
(
select nvl (tr.applied_to_entity_id, tr.source_entity_id) entity_id,
tr.source_application_id application_id,
sum (nvl (tr.acctd_unrounded_cr, 0)) - sum (nvl (tr.acctd_unrounded_dr, 0)) acctd_amount,
sum (nvl (tr.entered_unrounded_cr, 0)) - sum (nvl (tr.entered_unrounded_dr, 0)) entered_amount,
max(tr.gl_date) gl_date
from xla.xla_trial_balances tr
where 1=1
and tr.definition_code = 'AP_200_1001'
and tr.source_application_id = 200
and tr.gl_date <= fnd_date.canonical_to_date('2019-12-13') -- Data KG
group by nvl (tr.applied_to_entity_id, tr.source_entity_id),
tr.source_application_id
) trial,
ap_payment_schedules_all aps
where 1=1
and ai.invoice_id = 3568325
and nvl(xte.source_id_int_1, -99) = ai.invoice_id
and xte.ledger_id = 1001
and xte.entity_code = 'AP_INVOICES'
and xte.entity_id = trial.entity_id
and xte.application_id = trial.application_id
and ai.invoice_id = aps.invoice_id
)
select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id
Based on your comment I guess you need the below
select * from (select x.invoice_id, x.invoice_num, x.entity_id, x.acctd_amount, x.gl_date,
x.amount_remaining, x.gross_amount, x.due_date, x.payment_status_flag,
x.dni_opoznienia, aapl.days_start, aapl.days_to,
case
when x.dni_opoznienia between aapl.days_start and aapl.days_to then x.acctd_amount
else 0
end przedzial
from x,
ap_aging_periods aap,
ap_aging_period_lines aapl
where 1=1
and aap.period_name = 'TEST 5 okresow'
and aap.aging_period_id = aapl.aging_period_id)
where przedzial > 0;

SQL, search for true, false or both

I am currently trying to code an SQL search that can return TRUE, FALSE, or NEITHER. While the code I currently have works, I do not like the fact that I had to copy and paste a lot of code, and was wondering if there was a way to reduce the amount of code here.
DECLARE #FYear int = 2017
DECLARE #FQuarter char(2) = 'Q2'
DECLARE #FINANCIAL_GOAL_MET bit = NULL
IF(#FINANCIAL_GOAL_MET IS NULL)
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
ELSE
SELECT FYear,
FQuarter,
IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met
FROM Finances
WHERE (FYear = #FYear)
AND (FQuarter = #FQuarter)
AND FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET
You can do this in one query:
DECLARE #FYear int = 2017;
DECLARE #FQuarter char(2) = 'Q2';
DECLARE #FINANCIAL_GOAL_MET bit = NULL;
SELECT FYear, FQuarter,
(CASE WHEN FINANCIAL_GOAL_MET = 'TRUE' THEN 1 ELSE 0
END) AS Financial_Goal_Met
FROM Finances f
WHERE (FYear = #FYear) AND (FQuarter = #FQuarter) AND
(#FINANCIAL_GOAL_MET IS NULL OR FINANCIAL_GOAL_MET = #FINANCIAL_GOAL_MET);
For those not familiar with the bit type in SQL Server, 'TRUE' is accepted for comparison, even though it is a string.

Why can't I insert data to my table?

I created a table using this
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[DimRegion]') AND type in (N'U'))
DROP TABLE [DimRegion]
Go
Create Table DimRegion
(RegionViewKey int NOT NULL identity Primary Key,
RegionView varchar(10),
RegionViewCode varchar(10),
ActiveYear smallint,
SublocationString varchar(7)NULL,
SubLocationCode char(10)NOT NULL,
LocationCode char(10)NULL,
RegionCode char(10)NULL,
RegionGrpCode char(10)NULL,
DivisionCode char(10)NOT NULL,
DivisionGrpCode char(10)NULL,
SubLocationDescription char(50)NULL,
LocationDescription char(50)NULL,
RegionDescription char(50)NULL,
RegionGrpDescription char(50)NULL,
DivisionDescription char(50)NULL,
DivisionGrpDescription char(50)NULL)
And I inserted data using this script
insert into DWResourceTask.dbo.DimRegion --(2013)
Select
'Region1' as RegionView,
'R1' as RegionViewCode,
'2013' as ActiveYear,
sl.sublocationstring,
sl.subLocationCode,
l.locationcode,
r.regioncode,
rg.RegionGrpCode,
d.DivisionCode,
dg.DivisionGrpCode,
sl.SubLocationDescription,
l.LocationDescription,
r.regiondescription,
rg.RegionGrpDescription,
d.divisionDescription,
dg.DivisionGrpDescription
from SCSubLocation sl,
SCLocation l,
SCRegion r,
SCRegionGrp rg,
SCDivision d,
SCDivisionGrp dg
where l.LocationCode = sl.LocationCode
and r.RegionCode = l.RegionCode
and r.RegionGrpCode = rg.RegionGrpCode
and d.divisioncode = rg.divisioncode
and d.divisiongrpcode = dg.divisiongrpcode
But when I created this script below where it would only insert new and latest data, it gives me an error such as
Msg 102, Level 15, State 1, Line 33
Incorrect syntax near 'R1'.
Script:
insert into DWResourceTask.dbo.DimRegion --(2013)
Select
'Region1' as RegionView,
'R1' as RegionViewCode,
'2013' as ActiveYear,
sl.sublocationstring,
sl.subLocationCode,
l.locationcode,
r.regioncode,
rg.RegionGrpCode,
d.DivisionCode,
dg.DivisionGrpCode,
sl.SubLocationDescription,
l.LocationDescription,
r.regiondescription,
rg.RegionGrpDescription,
d.divisionDescription,
dg.DivisionGrpDescription
from SCSubLocation sl,
SCLocation l,
SCRegion r,
SCRegionGrp rg,
SCDivision d,
SCDivisionGrp dg
where l.LocationCode = sl.LocationCode
and r.RegionCode = l.RegionCode
and r.RegionGrpCode = rg.RegionGrpCode
and d.divisioncode = rg.divisioncode
and d.divisiongrpcode = dg.divisiongrpcode
and not exists(select * from DWResourceTask.dbo.DimRegion x
where(Region1=x.RegionView
R1=x.RegionViewCode
2013=x.ActiveYear
sl.sublocationstring=x.sublocationstring
sl.subLocationCode=x.subLocationCode
l.locationcode=x.locationcode
r.regioncode=x.regioncode
rg.RegionGrpCode=x.RegionGrpCode
d.DivisionCode=x.DivisionCode
dg.DivisionGrpCode=x.DivisionGrpCode
sl.SubLocationDescription=x.SubLocationDescription
l.LocationDescription=x.LocationDescription
r.regiondescription=x.regiondescription
rg.RegionGrpDescription=x.RegionGrpDescription
d.divisionDescription=x.divisionDescription
dg.DivisionGrpDescription=x.DivisionGrpDescription)
)
How do I fix this script on top where it only inserts latest data
It looks like your WHERE clause is missing the ANDs between parts of the condition:
...
where(Region1=x.RegionView
AND R1=x.RegionViewCode
AND 2013=x.ActiveYear
AND sl.sublocationstring=x.sublocationstring
AND sl.subLocationCode=x.subLocationCode
AND l.locationcode=x.locationcode
AND r.regioncode=x.regioncode
AND rg.RegionGrpCode=x.RegionGrpCode
AND d.DivisionCode=x.DivisionCode
AND dg.DivisionGrpCode=x.DivisionGrpCode
AND sl.SubLocationDescription=x.SubLocationDescription
AND l.LocationDescription=x.LocationDescription
AND r.regiondescription=x.regiondescription
AND rg.RegionGrpDescription=x.RegionGrpDescription
AND d.divisionDescription=x.divisionDescription
AND dg.DivisionGrpDescription=x.DivisionGrpDescription)
)