SQL Variable Changing Value - sql

I'm trying to rewrite the following code to use a variable instead of magic numbers:
SELECT tokenId,
IIF(LEN(ref) < 4, ref, REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-4) + SUBSTRING(ref, (LEN(ref)-3), LEN(ref))) as refMasked
FROM tokenBase
WHERE (refMasked is null or refMasked = '') AND ref is not null AND ref <> ''
I tried doing it like this:
DECLARE #NumberOfCharsAtEndOfStringToNotMask INTEGER
SET #NumberOfCharsAtEndOfStringToNotMask = 4 --Why do I need to set this to 2 for it to work?
SELECT tokenId,
IIF(LEN(ref) < #NumberOfCharsAtEndOfStringToNotMask, ref, REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask-1), LEN(ref))) as refMasked
FROM tokenBase
WHERE (refMasked is null or refMasked = '') AND ref is not null AND ref <> ''
However it doesn't work if I use #NumberOfCharsAtEndOfStringToNotMask = 4, I need to use 2 instead. Why is this?
If I use 4 then the last 6 chars of the string are left unmasked, however I need the last 4 chars to be unmasked. Using a value of 2 fixes this but I have no idea why.
EDIT
Amit has suggested I use the following code which works:
IIF(LEN(ref) < #NumberOfCharsAtEndOfStringToNotMask, ref,REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask+1),#NumberOfCharsAtEndOfStringToNotMask)) as refMasked
Why does this work? Why can't I just replace the use of 4 with a variable storing the value of 4?

Try this Dave:
DECLARE #C INTEGER = 4;
SELECT bpayreference
, LEN(bpayreference) As LengthOfString
, LEN(bpayreference) - #C AS MinusC
, SUBSTRING(bpayreference , (LEN(bpayreference) - #C) + 1 , (LEN(bpayreference) ) - (LEN(bpayreference) - #C))
, CASE
WHEN (LEN(bpayreference) < #C) THEN REPLICATE('*' , LEN(bpayreference) - #C)
ELSE
REPLICATE('*' , LEN(bpayreference) - #C )
+ SUBSTRING(bpayreference , (LEN(bpayreference) - #C) + 1 , (LEN(bpayreference) ) - (LEN(bpayreference) - #C))
END
FROM tokenbase

Replace your iif block with this one and see how you go
IIF(LEN(ref) < #NumberOfCharsAtEndOfStringToNotMask, ref,REPLICATE(CONVERT(NVARCHAR(20),'*'), LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask) + SUBSTRING(ref, (LEN(ref)-#NumberOfCharsAtEndOfStringToNotMask+1),#NumberOfCharsAtEndOfStringToNotMask)) as refMasked

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;

Can switch statements cause a 'Query is too Complex' error in MS Access 365?

As background, we are currently using Lotus Approach as our job schedule database. Out of fear that one day it'll cease working with newer versions of Windows, I've been searching for an alternative that isn't terribly dissimilar from Approach. One of the features in Approach that has been wonderful is that calculated fields are stored in the front end and has full access to all tables in the database, as well as other calculated fields without having to link them to forms, reports, or each other. I have yet to find a program that handles calculated fields in a similar manner, so I've moved to using queries in Access to beginning building these calculated fields (around 200 formulas).
That said, I have 4 tables and 3 queries, but I'm hitting a wall with one of the queries. In the query that's giving me the error, I think I've determined the problem has to do with 1 switch statement (AUDIT_JTD_EARNED_REV) as there are 3 other formulas that rely on this calculation and if I delete one of these (not all of them), then the query will run.
I have not used Access before in any meaningful way, so if there is a better way of doing it, then I'm all ears. Below are the 3 queries I'm using and the error is occurring in the Audit Calc query.
Audit Calc
SELECT Book.job_id,
(
Book.jtd_ti_cost - Book.audit_jtd_ti_cost + Book.jtd_eq_credit + Book.sdp_profit ) AS AUDIT_FCST_PROFIT_ADJ,
Book.book_jtd_cost - audit_fcst_profit_adj + ICalc.ic_audit_jtd_profit_adj
AS
AUDIT_JTD_COST,
Switch(Book.stat_cd = 'C', Book.jtd_gross_bill + Book.accrued_billing,
( Book.stat_cd = 'I'
AND
audit_jtd_cost + audit_fcst_profit >
Book.book_contract_amt * audit_pct_cmpl )
OR (
Book.stat_cd = 'A'
AND Book.job_type <> '2'
AND audit_pct_cmpl >= 0.2 ), Round(Book.book_contract_amt * audit_pct_cmpl, 2),
Book.stat_cd = 'A'
AND Book.job_type = '1'
AND audit_pct_cmpl < 0.2, audit_jtd_cost, true,
audit_jtd_cost + audit_fcst_profit)
AS AUDIT_JTD_EARNED_REV,
Book.book_contract_amt - audit_fcst_profit
AS AUDIT_FCST_COST,
Switch(Book.book_contract_amt < 1, 1, Book.job_type = 2,
Book.jtd_gross_bill - Book.accrued_billing / Book.book_contract_amt, true,
audit_jtd_cost / audit_fcst_cost)
AS AUDIT_PCT_CMPL,
Nz(Book.fcst_job_profit)
+ audit_fcst_profit_adj
+ Nz(ICalc.ic_audit_fcst_profit)
AS AUDIT_FCST_PROFIT,
Round(audit_jtd_earned_rev - Nz(Book.prior_adt_rev), 2)
AS AUDIT_YTD_EARNED_REV,
audit_jtd_cost + audit_addl_loss - Nz(Book.prior_adt_cost)
AS AUDIT_YTD_COST,
audit_ytd_earned_rev - audit_ytd_cost
AS AUDIT_YTD_EARNED_PROFIT,
Switch(Book.prime_job_id IS NULL
OR ( Nz(Book.fcst_job_profit, 0) - Nz(ICBook.fcst_job_profit, 0) ) > 0
OR Book.stat_cd <> 'A'
OR
( Book.book_contract_amt - audit_fcst_cost ) >= 0, 0, true,
audit_fcst_profit - audit_jtd_cost + audit_jtd_earned_rev)
AS AUDIT_ADDL_LOSS,
Iif(Book.stat_cd <> "a", 0, audit_fcst_cost - audit_jtd_cost)
AS
AUDIT_FCST_COST_TO_CMPL,
audit_fcst_profit / Iif(Book.job_type = 2,
Book.book_contract_amt, audit_fcst_cost)
AS AUDIT_PROFIT_PCT,
audit_jtd_earned_rev - audit_jtd_cost + audit_addl_loss
AS
AUDIT_JTD_EARNED_PROFIT,
audit_jtd_earned_rev - Book.jtd_gross_bill - Book.accrued_billing + Nz(Book.jtd_ret_amt) AS AUDIT_OVER_UNDER_BILLING
FROM ([book calc] AS Book
LEFT JOIN [book calc] AS ICBook
ON Book.job_id = ICBook.prime_job_id)
LEFT JOIN [interco calc] AS ICalc
ON Book.job_id = ICalc.prime_job_id;
Interco Calc
SELECT [book calc].prime_job_id
AS PRIME_JOB_ID,
[book calc].job_id
AS SUB_JOB_ID,
[book calc].jtd_ti_cost - [book calc].audit_jtd_ti_cost +
[book calc].jtd_eq_credit + [book calc].sdp_profit
AS IC_AUDIT_FCST_PROFIT_ADJ,
[book calc].fcst_job_profit
+ ic_audit_fcst_profit_adj
AS IC_AUDIT_FCST_PROFIT,
Round([book calc].jtd_mat_cost
+ [book calc].jtd_sub_cost
+ [book calc].jtd_oth_cost
+ [book calc].jtd_gl_cost
+ [book calc].jtd_eq_cost
+ [book calc].jtd_labor_cost
+ [book calc].accrued_cost
+ Nz([book calc].prior_adt_ti)
+ [book calc].audit_ytd_ti_cost - Nz([book calc].prior_eq_credit) -
[book calc].ytd_eq_credit + [book calc].jtd_sdp_cost -
[book calc].sdp_profit, 2)
AS IC_AUDIT_JTD_COST,
ic_audit_jtd_cost - ( [book calc].jtd_gross_bill
+ [book calc].accrued_billing )
AS IC_AUDIT_JTD_PROFIT_ADJ,
Iif([book calc].book_contract_amt < 1, 1,
Iif([book calc].job_type = 2, ( [book calc].gross_bill
+ [book calc].accrued_billing ) /
[book calc].book_contract_amt, ic_audit_jtd_cost / ic_audit_fcst_cost)) AS IC_AUDIT_PCT_CMPL,
[book calc].book_contract_amt - ic_audit_fcst_profit
AS IC_AUDIT_FCST_COST
FROM [book calc]
WHERE ( [book calc].prime_job_id ) IS NOT NULL;
And finally Book Calc
SELECT fsjob.*,
eq_aed.eq_aed_prem
AS EQ_AED_PREM,
eq_aed.eq_aed_chrg
AS EQ_AED_CHRG,
Nz(fsjob.gross_bill)
+ Nz(fsjob.prior_gross_bill)
+ Nz(fsjob.prior_accr_bill)
AS JTD_GROSS_BILL,
Round(Nz(fsjob.sc_cost) + Nz(fsjob.prior_sc_cost), 2)
AS JTD_SUB_COST,
Nz(fsjob.labor_cost)
+ Nz(fsjob.prior_labor_cost)
AS JTD_LABOR_COST,
Nz(fsjob.oth_cost)
+ Nz(fsjob.prior_oth_cost)
AS JTD_OTH_COST,
Nz(fsjob.mat_cost)
+ Nz(fsjob.prior_mat_cost)
AS JTD_MAT_COST,
Nz(fsjob.eq_cost) + Nz(fsjob.prior_eq_cost)
AS JTD_EQ_COST,
Nz(fsjob.gl_cost) + Nz(fsjob.prior_gl_cost)
AS JTD_GL_COST,
Nz(fsjob.ti_cost) + Nz(fsjob.prior_ti_cost)
AS JTD_TI_COST,
Iif(( fsjob.sdp_cd = 'SDP'
AND fsjob.stat_cd = 'I' )
OR ( fsjob.sdp_cd = 'SDP'
AND jtd_gross_bill > 0
AND fsjob.stat_cd = 'A'
AND jtd_sub_cost > 0 ), Round(variable.sdp_pct *
Nz(fsjob.fcst_sc_cost), 2), 0)
AS
JTD_SDP_COST,
Switch(fsjob.stat_cd = 'I', Nz(fsjob.contract_amt, 0) - jtd_gross_bill, true, Nz(fsjob.accr_bill_adj, 0))
AS ACCRUED_BILLING,
Switch(fsjob.stat_cd = 'C', jtd_gross_bill + accrued_billing, true, Nz(fsjob.contract_amt, 0))
AS BOOK_CONTRACT_AMT,
Iif(fsjob.stat_cd = 'I', Round(
book_contract_amt - Nz(fsjob.fcst_job_profit)
- jtd_sub_cost + jtd_labor_cost + jtd_oth_cost + jtd_mat_cost + jtd_eq_cost + jtd_gl_cost + jtd_ti_cost + jtd_sdp_cost, 2), Nz(fsjob.accr_cost_adj))
AS ACCRUED_COST,
Round(jtd_sub_cost + jtd_labor_cost + jtd_oth_cost
+ jtd_mat_cost + jtd_eq_cost + jtd_gl_cost
+ jtd_ti_cost + jtd_sdp_cost + accrued_cost, 2)
AS BOOK_JTD_COST,
Round(book_contract_amt - Nz(fsjob.fcst_job_profit), 2)
AS BOOK_FCST_COST,
Iif(fsjob.stat_cd = 'C'
OR
book_contract_amt < 1, 1,
Iif(fsjob.job_type = 2, ( accrued_billing + jtd_gross_bill ) / book_contract_amt, book_jtd_cost / book_fcst_cost))
AS BOOK_PCT_CMPL,
Iif(fsjob.stat_cd <> 'A', Round(jtd_gross_bill + accrued_billing, 2),
Iif(fsjob.job_type = 2,
Iif(( book_jtd_cost + Nz(fsjob.fcst_job_profit) ) < (
book_contract_amt * book_pct_cmpl ),
Nz(fsjob.fcst_job_profit) + book_jtd_cost, Round(
book_pct_cmpl * book_contract_amt, 2)),
Iif(Nz(fsjob.fcst_job_profit) < 0, Nz(fsjob.fcst_job_profit) + book_jtd_cost, Iif(book_pct_cmpl < 0.195, book_jtd_cost,
Round(
book_pct_cmpl * book_contract_amt, 2)))))
AS
BOOK_JTD_EARNED_REV,
( book_jtd_earned_rev - book_jtd_cost )
AS BOOK_JTD_PROFIT,
Iif(fsjob.stat_cd = 'C', book_jtd_profit, Nz(fsjob.fcst_job_profit))
AS
BOOK_FCST_PROFIT,
( book_contract_amt - book_fcst_profit - book_jtd_cost )
AS BOOK_COST_TO_CMPL,
( Nz(fsjob.prior_bk_rev) - Nz(fsjob.prior_bk_cost) )
AS BOOK_PRIOR_PROFIT,
Round(book_jtd_cost - Nz(fsjob.prior_bk_cost), 2)
AS BOOK_YTD_COST,
Round(book_jtd_earned_rev - Nz(fsjob.prior_bk_rev), 2)
AS BOOK_YTD_EARNED_REV,
( book_ytd_earned_rev - book_ytd_cost )
AS BOOK_YTD_PROFIT,
Iif(fsjob.stat_cd = 'C', 0, Nz(fsjob.fcst_ye_labor) - jtd_labor_cost)
AS
LABOR_COST_TO_CMPL,
Round(jtd_gross_bill + accrued_billing - book_jtd_earned_rev, 2)
AS
BOOK_EXCESS_BILLING,
Round(Iif(( fsjob.sdp_cd = 'SDP'
AND fsjob.stat_cd = 'I' )
OR ( fsjob.sdp_cd = 'SDP'
AND Nz(jtd_gross_bill) > 0
AND fsjob.stat_cd = 'A'
AND
Nz(jtd_sub_cost) > 0 ), variable.sdp_pct * Nz(fsjob.fcst_sc_cost), 0), 2)
AS
SDP_REV,
Round(Iif(fsjob.sdp_cd IS NOT NULL
AND
fsjob.stat_cd <> 'C',
Iif(Nz(fsjob.fcst_sc_cost) > Nz(jtd_sub_cost),
Nz(fsjob.fcst_sc_cost) * variable.sdp_pct, Nz(jtd_sub_cost) * variable.sdp_pct), 0), 2)
AS FCST_SDP_REV,
Round(Iif(fsjob.sdp_cd IS NOT NULL
AND
fsjob.stat_cd <> 'C',
Nz(fsjob.sc_cost) / variable.ytd_sdp_sub_cost * variable.ytd_sdp_exp, 0), 2)
AS SDP_EXP,
( Nz(sdp.prior_cost) + Nz(sdp.curr_cost)
+ Nz(sdp.curr_ap) - Nz(sdp.prior_ap) + sdp_exp )
AS JTD_SDP_EXP,
Iif(fsjob.sdp_cd <> 'SDP'
OR fsjob.stat_cd = 'C', 0, Round(Nz(fsjob.fcst_sc_cost) - jtd_sub_cost, 2))
AS SUB_COST_TO_CMPL,
fcst_sdp_rev - jtd_sdp_exp - fcst_sdp_addl_reserve_amt
AS FCST_SDP_PROFIT,
sdp_rev - jtd_sdp_exp
AS SDP_PROFIT,
Iif(book_pct_cmpl < 0.195, Round(( fcst_sdp_rev - jtd_sdp_exp ) * 0.5, 2), 0)
AS
FCST_SDP_ADDL_RESERVE_AMT,
Iif(Nz(fsjob.fcst_job_profit) < 0, fcst_sdp_profit - Nz(fsjob.prior_sdp_credit), Iif(book_pct_cmpl < 0.195, 0,
Round(
book_pct_cmpl * fcst_sdp_profit - Nz(fsjob.prior_sdp_credit), 2)))
AS
YTD_SDP_CREDIT,
Iif(fsjob.stat_cd = 'C', fcst_sdp_profit,
Iif(Nz(fsjob.fcst_job_profit) < 0, fcst_sdp_profit - Nz(fsjob.prior_sdp_credit),
Iif(Nz(fsjob.fcst_ye_pct_cmpl) < 0.195, 0,
Round(Nz(fsjob.fcst_ye_pct_cmpl) * fcst_sdp_profit - Nz(fsjob.prior_sdp_credit), 2)))) AS FCST_SDP_CREDIT,
sdp_profit - ytd_sdp_credit - Nz(fsjob.prior_sdp_credit)
AS YTD_SDP_RESERVE_AMT,
ytd_sdp_credit + Nz(fsjob.prior_sdp_credit)
AS JTD_SDP_CREDIT,
Round(Nz(eq_aed.eq_aed_chrg) / variable.ytd_eq_rev * variable.ytd_eq_profit, 2)
AS YTD_EQ_CREDIT,
ytd_eq_credit + Nz(fsjob.prior_eq_credit)
AS JTD_EQ_CREDIT,
Round(fsjob.ti_pct * Nz(fsjob.fcst_labor_cost), 2)
AS FCST_TI_COST,
audit_ytd_ti_cost + Nz(fsjob.prior_adt_ti)
AS AUDIT_JTD_TI_COST,
Switch(fsjob.ti_pct = 0.1, Nz(fsjob.ti_cost), true,
Round((jtd_labor_cost-Nz(fsjob.prior_labor_cost))*variable.actual_ti_pct, 2)
+ Nz(fsjob.wc_cost, 0))
AS AUDIT_YTD_TI_COST
FROM ((fsjob
LEFT JOIN variable
ON fsjob.var_ctrl_num = variable.var_ctrl_num)
LEFT JOIN eq_aed
ON fsjob.job_id = eq_aed.job_id)
LEFT JOIN sdp
ON fsjob.job_id = sdp.job_id;
The deepest nested IIF in all of these is only 3 deep and the most complex Switch statement only has 4 options. And the fields used in these statements are not overly complex, either. I've been fighting to simplify this for about a week and don't believe I can make it any more concise.
Thanks in advance.

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;

Query Parameters not working

Working on a query here in SSRS and when I use the #Date parameters it doesnt seem to work, I dont get an error but it doesnt return values. When I take the =#Date value out of it, seems to run fine. Any Ideas on how I can correct this? I want to be able to input a name and date.
Thanks
SELECT TOP (100) PERCENT A.__$start_lsn, A.__$seqval, A.__$operation, A.__$update_mask, A.t_Refcntd, A.t_Refcntu, A.t_cbrn, A.t_ccon, A.t_ccor, A.t_ccrs, A.t_ccty, A.t_ccur,
A.t_cdec, A.t_cfrw, A.t_cfsg, A.t_clan, A.t_comp, A.t_corg, A.t_cotp, A.t_cpay, A.t_cplp, A.t_creg, A.t_ctrj, A.t_cvyn, A.t_cwar, A.t_ddat, A.t_ddtc, A.t_egen, A.t_odat,
A.t_odis, A.t_orno, A.t_prno, A.t_pspr, A.t_pstx, A.t_ragr, A.t_ratf, A.t_ratp, A.t_refa, A.t_refb, A.t_suno, A.t_txta, A.t_txtb, A.tran_begin_time, A.tran_end_time,
B.event_time, B.event_time_local, B.sequence_number, B.action_id, B.succeeded, B.permission_bitmask, B.is_column_permission, B.session_id,
B.server_principal_id, B.database_principal_id, B.target_server_principal_id, B.target_database_principal_id, B.object_id, B.class_type,
B.session_server_principal_name, B.server_principal_name, B.server_principal_sid, B.database_principal_name, B.target_server_principal_name,
B.target_server_principal_sid, B.target_database_principal_name, B.server_instance_name, B.database_name, B.schema_name, B.object_name, B.statement,
B.additional_information, B.file_name, B.audit_file_offset, CONVERT(VARCHAR(10), A.tran_end_time, 110) AS GenericDate
FROM dbo.ttdpur040101_CT AS A INNER JOIN
dbo.ttdpur040101_Audit AS B ON NOT (A.tran_begin_time > B.event_time_local OR
A.tran_end_time < B.event_time_local) AND (A.__$operation = 2 AND B.action_id = 'IN' OR
(A.__$operation = 3 OR
A.__$operation = 4) AND B.action_id = 'UP' OR
A.__$operation = 1 AND B.action_id = 'DL') AND B.class_type = 'U'
WHERE (B.server_principal_name = #Name) and (CONVERT(VARCHAR(10), A.tran_end_time, 110) = #Date)
ORDER BY B.event_time_local
If you are going to compare them, the formats need to match. Change your WHERE to:
WHERE (B.server_principal_name = #Name)
and (CONVERT(VARCHAR(10), A.tran_end_time, 110) = (CONVERT(VARCHAR(10),#Date, 110))

T-SQL update with switch-case statement

I want implement this pseudocode in t-sql
UPDATE Resources SET [Path]= CASE ([Path].Substring([Path].LastIndexOf('.')))
WHEN '.jpg' THEN '/image.jpg'
WHEN '.png' THEN '/image.jpg'
WHEN '.avi' THEN '/video.jpg'
WHEN '.mkv' THEN '/video.jpg'
for it I use this solution
UPDATE Resources SET [Path] = CASE (SUBSTRING([Path], LEN([Path]) - CHARINDEX('.', REVERSE([Path])) + 1, 3))
WHEN '.jpg' THEN '/image.jpg'
WHEN '.png' THEN '/image.jpg'
WHEN '.avi' THEN '/video.jpg'
WHEN '.mkv' THEN '/video.jpg'
END
but it is does not return expected result.
Can anyone give me working version please?
UPDATE
Resources
SET
Path = CASE SUBSTRING(Path, LEN(Path) - CHARINDEX('.', REVERSE(Path)) + 1, 4)
WHEN '.jpg' THEN '/image.jpg'
WHEN '.png' THEN '/image.jpg'
WHEN '.avi' THEN '/video.jpg'
WHEN '.mkv' THEN '/video.jpg'
END
Instead of SUBSTRING([Path], LEN([Path]) - CHARINDEX('.', REVERSE([Path])) + 1, 3),
try using lower(right([Path], 4))
Your read of the extension is wrong, instead try:
SUBSTRING(Path, LEN(Path) - CHARINDEX('.', REVERSE(Path)) + 1, LEN(Path))
(Using LEN(Path) as the read length; fine if it overflows the end of the string and allows for n-character extensions)
Try using the ParseName
UPDATE Resources SET [Path] = CASE (Parsename(Path,1))
WHEN 'jpg' THEN '/image.jpg'
WHEN 'png' THEN '/image.jpg'
WHEN 'avi' THEN '/video.jpg'
WHEN 'mkv' THEN '/video.jpg'
END
UPDATE Resources SET ThumbnailPath = CASE SUBSTRING(ThumbnailPath, LEN(ThumbnailPath) - CHARINDEX('.', REVERSE(ThumbnailPath)) + 1, LEN(ThumbnailPath))
WHEN '.doc' THEN #root + '/doc.png'
WHEN '.docx' THEN #root + '/doc.png'
WHEN '.jpg' THEN #root + '/image.png'
WHEN '.jpeg' THEN #root + '/image.png'
WHEN '.gif' THEN #root + '/image.png'
WHEN '.png' THEN #root + '/image.png'
WHEN '.ppt' THEN #root + '/ppt.png'
WHEN '.pptx' THEN #root + '/ppt.png'
WHEN '.pdf' THEN #root + '/pdf.png'
ELSE #root + '/other.png'
END
thank you I finaly use this
This script will assure that you do not update all rows every time you run the script. It will only update changes.
UPDATE r
SET ThumbnailPath = newvalue
FROM Resources r
cross apply
(SELECT right(ThumbnailPath, patindex('%_.%', reverse(ThumbnailPath))) T) a
cross apply
(SELECT CASE
WHEN a.T in ('doc','docx' ) THEN #root + '/doc.png'
WHEN a.T in ('jpg','jpeg','gif','png') THEN #root + '/image.png'
WHEN a.T in ('ppt','pptx') THEN #root + '/ppt.png'
WHEN a.T = 'pdf' THEN '/pdf.png'
ELSE #root + '/other.png'
END newvalue) b
WHERE r.ThumbnailPath <> b.newvalue