Slow Query only for specific values in a Where IN Clause - sql-server

I wonder if anyone has come across this behaviour before in the following query if I filter on "i.InspectionTypeID IN (x)" if x results in a large number (like about 2/3 of the entire result set of about 600 000) It takes a significantly longer amount of time to return even no results (15-30 seconds vs instantly otherwise). I can include the query and the execution plans if that helps. I can see a few differences between the queries but no idea how to refactor to improve it. We have indexes around the place that should (and have) improved performance in other places but I seem to be stuck on this one. Indexes don't appear to affect performance. At least what I tried.
Slow Query Plan: https://www.brentozar.com/pastetheplan/?id=SyBDgxSeO
EDIT: New Plan and Updated the Query as per advice from #charlieface
Here's the query:
declare #currentUserID int = 1018
declare #currentCompanyID int = 43
declare #status int = 0
declare #pageSize int = 2147483647
declare #pageNumber int = 1
DECLARE #notPreferredAssetIDsTable TABLE (id INT)
INSERT INTO #notPreferredAssetIDsTable
SELECT RecordID FROM SettingList sl
WHERE SettingID = (SELECT TOP 1 ID FROM Setting
WHERE SystemUserID = #currentUserID AND Name = 'Preferred Assets' AND Status = #status)
AND Value = '0'
AND Status = #status
SELECT i.ID As ID, a.AssetTypeID, at.Name as AssetTypeName, a.Code as AssetCode, a.Name as AssetName, CASE WHEN sections.SectionCount = 1 THEN cr.SectionName ELSE '' END as SectionName, c.Name as ContractName, reg.Name as RegionName, i.Carriageway,
startStatus.StatusDate as StartDate, startPoint.Name as StartPointName, i.ChainageFrom,
CASE WHEN i.Carriageway IS NULL THEN NULL ELSE i.ChainageFrom - (CASE WHEN i.Carriageway = 0 THEN startPoint.Forward ELSE startPoint.Reverse END) END StartDistancePast,
completedStatus.StatusDate As EndDate, endPoint.Name as EndPointName, i.ChainageTo,
CASE WHEN i.Carriageway IS NULL THEN NULL ELSE i.ChainageTo - (CASE WHEN i.Carriageway = 0 THEN endPoint.Forward ELSE endPoint.Reverse END) END EndDistancePast,
CASE WHEN i.Carriageway IS NULL THEN '' ELSE (CASE WHEN (ISNULL(OtherDirectionInspection.ID, 0) > 0) THEN 'Forward/Reverse'
WHEN i.Carriageway = 0 THEN 'Forward' ELSE 'Reverse' END) END as CarriagewayName,
dbo.GetInspectionTypeNamesForInspectionID(i.ID) AS InspectionTypeName, JobCount.Total As JobCount, i.CreatedDate,
CreatedUserName.DisplayName as CreatedUserName, AssignedUserName.DisplayName as AssignedUserName,
i.Comments, i.EntireRoad, i.PlannedDate, latestStatus.InspectionStatus AS LatestInspectionStatus, completedStatus.StatusDate AS CompletedDate, it.CompanyID as InspectionTypeCompanyID, i.ContractID, i.InspectionTypeID, sections.SectionCount,
it.Category as InspectionTypeCategory, latestStatus.ModifiedDeviceID as DeviceID, latestStatus.ModifiedUserID as LatestStatusModifiedUserID, i.JobID, i.CapitalWorkID, cw.Name as CapitalWorkName, AssignedUser.Name as AssignedUserEmail,
InspectionRouteName.Name as InspectionRouteName, i.InspectionGroupID,
il.Location AS InspectionLocation,
i.OtherDirectionInspectionID , CustomText1 , CustomBit1 , CustomDate1 , CustomNumber1 , CustomReferenceItemID1 , CustomText2 , CustomBit2 , CustomDate2 , CustomNumber2 , CustomReferenceItemID2 , CustomText3 , CustomBit3 , CustomDate3 , CustomNumber3 , CustomReferenceItemID3 , CustomText4 , CustomBit4 , CustomDate4 , CustomNumber4 , CustomReferenceItemID4 , CustomText5 , CustomBit5 , CustomDate5 , CustomNumber5 , CustomReferenceItemID5 , CustomText6 , CustomBit6 , CustomDate6 , CustomNumber6 , CustomReferenceItemID6 , CustomText7 , CustomBit7 , CustomDate7 , CustomNumber7 , CustomReferenceItemID7 , CustomText8 , CustomBit8 , CustomDate8 , CustomNumber8 , CustomReferenceItemID8 , CustomText9 , CustomBit9 , CustomDate9 , CustomNumber9 , CustomReferenceItemID9 , CustomText10 , CustomBit10 , CustomDate10 , CustomNumber10 , CustomReferenceItemID10 , CustomText11 , CustomBit11 , CustomDate11 , CustomNumber11 , CustomReferenceItemID11 , CustomText12 , CustomBit12 , CustomDate12 , CustomNumber12 , CustomReferenceItemID12 , CustomText13 , CustomBit13 , CustomDate13 , CustomNumber13 , CustomReferenceItemID13 , CustomText14 , CustomBit14 , CustomDate14 , CustomNumber14 , CustomReferenceItemID14 , CustomText15 , CustomBit15 , CustomDate15 , CustomNumber15 , CustomReferenceItemID15 , CustomText16 , CustomBit16 , CustomDate16 , CustomNumber16 , CustomReferenceItemID16 , CustomText17 , CustomBit17 , CustomDate17 , CustomNumber17 , CustomReferenceItemID17 , CustomText18 , CustomBit18 , CustomDate18 , CustomNumber18 , CustomReferenceItemID18 , CustomText19 , CustomBit19 , CustomDate19 , CustomNumber19 , CustomReferenceItemID19 , CustomText20 , CustomBit20 , CustomDate20 , CustomNumber20 , CustomReferenceItemID20 , CustomText21 , CustomBit21 , CustomDate21 , CustomNumber21 , CustomReferenceItemID21 , CustomText22 , CustomBit22 , CustomDate22 , CustomNumber22 , CustomReferenceItemID22 , CustomText23 , CustomBit23 , CustomDate23 , CustomNumber23 , CustomReferenceItemID23 , CustomText24 , CustomBit24 , CustomDate24 , CustomNumber24 , CustomReferenceItemID24 , CustomText25 , CustomBit25 , CustomDate25 , CustomNumber25 , CustomReferenceItemID25 , CustomText26 , CustomBit26 , CustomDate26 , CustomNumber26 , CustomReferenceItemID26 , CustomText27 , CustomBit27 , CustomDate27 , CustomNumber27 , CustomReferenceItemID27 , CustomText28 , CustomBit28 , CustomDate28 , CustomNumber28 , CustomReferenceItemID28 , CustomText29 , CustomBit29 , CustomDate29 , CustomNumber29 , CustomReferenceItemID29 , CustomText30 , CustomBit30 , CustomDate30 , CustomNumber30 , CustomReferenceItemID30 , CustomText31 , CustomBit31 , CustomDate31 , CustomNumber31 , CustomReferenceItemID31 , CustomText32 , CustomBit32 , CustomDate32 , CustomNumber32 , CustomReferenceItemID32 , CustomText33 , CustomBit33 , CustomDate33 , CustomNumber33 , CustomReferenceItemID33 , CustomText34 , CustomBit34 , CustomDate34 , CustomNumber34 , CustomReferenceItemID34 , CustomText35 , CustomBit35 , CustomDate35 , CustomNumber35 , CustomReferenceItemID35 , CustomText36 , CustomBit36 , CustomDate36 , CustomNumber36 , CustomReferenceItemID36 , CustomText37 , CustomBit37 , CustomDate37 , CustomNumber37 , CustomReferenceItemID37 , CustomText38 , CustomBit38 , CustomDate38 , CustomNumber38 , CustomReferenceItemID38 , CustomText39 , CustomBit39 , CustomDate39 , CustomNumber39 , CustomReferenceItemID39 , CustomText40 , CustomBit40 , CustomDate40 , CustomNumber40 , CustomReferenceItemID40 , CustomText41 , CustomBit41 , CustomDate41 , CustomNumber41 , CustomReferenceItemID41 , CustomText42 , CustomBit42 , CustomDate42 , CustomNumber42 , CustomReferenceItemID42 , CustomText43 , CustomBit43 , CustomDate43 , CustomNumber43 , CustomReferenceItemID43 , CustomText44 , CustomBit44 , CustomDate44 , CustomNumber44 , CustomReferenceItemID44 , CustomText45 , CustomBit45 , CustomDate45 , CustomNumber45 , CustomReferenceItemID45 , CustomText46 , CustomBit46 , CustomDate46 , CustomNumber46 , CustomReferenceItemID46 , CustomText47 , CustomBit47 , CustomDate47 , CustomNumber47 , CustomReferenceItemID47 , CustomText48 , CustomBit48 , CustomDate48 , CustomNumber48 , CustomReferenceItemID48 , CustomText49 , CustomBit49 , CustomDate49 , CustomNumber49 , CustomReferenceItemID49 , CustomText50 , CustomBit50 , CustomDate50 , CustomNumber50 , CustomReferenceItemID50
FROM Inspection i
INNER JOIN InspectionType it On i.InspectionTypeID = it.ID
INNER JOIN SystemUser CreatedUser On CreatedUser.ID = i.CreatedUserID
INNER JOIN Contract c On i.ContractID = c.ID
INNER JOIN Region reg On c.RegionID = reg.ID
INNER JOIN InspectionLocation il ON il.InspectionID = i.ID
LEFT OUTER JOIN Asset a On i.AssetID = a.ID
LEFT OUTER JOIN SystemUser AssignedUser On AssignedUser.ID = i.AssignedUserID
LEFT OUTER JOIN Road r On i.RoadID = r.ID
LEFT OUTER JOIN AssetType at On it.AssetTypeID = at.ID
LEFT OUTER JOIN Point startPoint On i.StartPointID = startPoint.ID
LEFT OUTER JOIN Point endPoint On i.EndPointID = endPoint.ID
LEFT OUTER JOIN CapitalWork cw On i.CapitalWorkID = cw.ID
CROSS APPLY dbo.GetNameForUser_Inline(i.CreatedUserID, i.ContractID, #currentCompanyID, 0) As CreatedUserName
OUTER APPLY dbo.GetNameForUser_Inline(i.AssignedUserID, i.ContractID, #currentCompanyID, 0) As AssignedUserName
OUTER APPLY
(
SELECT TOP 1 SectionName
FROM ContractRoad cr
WHERE cr.RoadID = r.ID
AND cr.ContractID = i.ContractID
AND ((i.Carriageway = 0 AND i.ChainageFrom < cr.ChainageToForward AND cr.ChainageFromForward < i.ChainageTo)
OR (i.Carriageway = 1 AND i.ChainageFrom < cr.ChainageFromReverse AND cr.ChainageToReverse < i.ChainageTo))
AND cr.Status = #status
) cr
OUTER APPLY
(
SELECT count(SectionName) as SectionCount
FROM ContractRoad cr
WHERE cr.RoadID = r.ID
AND cr.ContractID = i.ContractID
AND ((i.Carriageway = 0 AND i.ChainageFrom < cr.ChainageToForward AND cr.ChainageFromForward < i.ChainageTo)
OR (i.Carriageway = 1 AND i.ChainageFrom < cr.ChainageFromReverse AND cr.ChainageToReverse < i.ChainageTo))
AND cr.Status = #status
) sections
OUTER APPLY
(
SELECT TOP 1 StatusDate, LocalTime.LocalTime as StatusDateLocal
FROM InspectionStatus
CROSS APPLY tzdb.UtcToLocal_Inline(StatusDate, 'Australia/Sydney') as LocalTime
WHERE Status = #status
AND InspectionID = i.ID
AND InspectionStatus = 1
ORDER BY StatusDate
) startStatus
OUTER APPLY
(
SELECT TOP 1 StatusDate, LocalTime.LocalTime as StatusDateLocal
FROM InspectionStatus
CROSS APPLY tzdb.UtcToLocal_Inline(StatusDate, 'Australia/Sydney') as LocalTime
WHERE Status = #status
AND InspectionID = i.ID
AND InspectionStatus = 5
ORDER BY StatusDate
) completedStatus
OUTER APPLY
(
SELECT TOP 1 ID, StatusDate, InspectionStatus, ModifiedDeviceID, ModifiedUserID
FROM InspectionStatus
WHERE Status = #status AND InspectionStatus.InspectionStatus <> 7
AND InspectionID = i.ID
ORDER BY CASE WHEN InspectionStatus.InspectionStatus = 6 THEN 1 ELSE 0 END, StatusDate DESC
) latestStatus
OUTER APPLY
(
SELECT COUNT(ID) As Total FROM Job
WHERE InspectionID = i.ID
AND ParentJobID IS NULL
AND Status = #status
) JobCount
OUTER APPLY
(
SELECT i2.ID
FROM dbo.Inspection i2
WHERE i2.OtherDirectionInspectionID = i.ID
AND Status = #status
) OtherDirectionInspection
OUTER APPLY
(
SELECT TOP 1 ir.Name FROM InspectionRoute ir
INNER JOIN InspectionGroup ig ON ig.InspectionRouteID = ir.ID
WHERE ir.Status = 0
AND ir.CompanyID = 43
AND ig.Status = 0
AND ig.ID = i.InspectionGroupID
) InspectionRouteName
WHERE i.Status = 0 AND i.ParentInspectionID IS NULL
AND il.Status = 0
--AND ((i.AssetID IS NOT NULL AND i.AssetID NOT IN (SELECT ID FROM #notPreferredAssetIDsTable)) OR i.AssetID IS NULL)
AND it.Category <> 2
AND c.IsArchived = 0
AND it.AssetTypeID = 3 AND a.AssetTypeID IS NOT NULL AND a.AssetTypeID = 3
AND i.InspectionTypeID IN (3)
AND i.ContractID IN (90,118)
AND (latestStatus.InspectionStatus IN (5,6,1,2,3) OR completedStatus.StatusDate IS NOT NULL OR latestStatus.InspectionStatus IS NULL)
AND ((completedStatus.StatusDateLocal >= '2021-02-01 00:00:00' AND completedStatus.StatusDateLocal <= '2021-02-05 23:59:59') OR (i.PlannedDate >= '2021-02-01 00:00:00' AND i.PlannedDate <= '2021-02-05 23:59:59') OR (i.CreatedDate >= '2021-02-01 00:00:00' AND i.CreatedDate <= '2021-02-05 23:59:59' AND (latestStatus.InspectionStatus not in (6, 5) OR latestStatus.InspectionStatus IS NULL)))
AND ((CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 43) OR (CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 1
AND i.ContractID IN (90,118)) OR (CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 79
AND i.ContractID IN (90)) OR (CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 80
AND i.ContractID IN (90)) OR (CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 81
AND i.ContractID IN (90)) OR (CASE WHEN i.AssignedUserID IS NULL THEN CreatedUser.CompanyID ELSE AssignedUser.CompanyID END = 82
AND i.ContractID IN (90)))
ORDER BY ID
OFFSET #pageSize * (#pageNumber - 1) ROWS
FETCH NEXT #pageSize ROWS ONLY
OPTION (RECOMPILE)

Related

How can I show active sub-organizations with an inactive organization (tree in SQL Server)

I have a tree with active and inactive organizations, and I have a search.
If you choose an inactive organization, you'll only see inactive organizations in the tree.
If I have a sub-organization (child) of an inactive organization (parent), how can I show active sub-organizations with an inactive organization
WITH h$cte AS
(
SELECT
ORGANIZATIONS.ORGANIZATION_ID ,
ORGANIZATIONS.PARENT_ID ,
ORGANIZATIONS.TITLE ,
ORGANIZATIONS.ARABIC_TITLE ,
ORGANIZATION_TYPES.ORGANIZATION_TYPE_ID ,
ORGANIZATION_TYPES.TITLE AS TITLE$2 ,
ORGANIZATION_TYPES.ARABIC_TITLE AS ARABIC_TITLE$2 ,
ORGANIZATIONS.IS_ACTIVE ,
1 Level ,
CASE WHEN #pLANGUAGE = 0
THEN CAST ('/' + ORGANIZATIONS.TITLE AS NVARCHAR(MAX))
ELSE CAST ('/' + ORGANIZATIONS.ARABIC_TITLE AS NVARCHAR(MAX))
END sort_path
FROM
ERP.ORGANIZATIONS
INNER JOIN
ERP.ORGANIZATION_TYPES ON ORGANIZATIONS.ORGANIZATION_TYPE_ID = ORGANIZATION_TYPES.ORGANIZATION_TYPE_ID
WHERE
ORGANIZATIONS.PARENT_ID IS NULL
UNION ALL
SELECT
ORGANIZATIONS.ORGANIZATION_ID ,
ORGANIZATIONS.PARENT_ID ,
ORGANIZATIONS.TITLE ,
ORGANIZATIONS.ARABIC_TITLE ,
ORGANIZATION_TYPES.ORGANIZATION_TYPE_ID ,
ORGANIZATION_TYPES.TITLE AS TITLE$2 ,
ORGANIZATION_TYPES.ARABIC_TITLE AS ARABIC_TITLE$2 ,
ORGANIZATIONS.IS_ACTIVE ,
h$cte.Level + 1 Level ,
CASE WHEN #pLANGUAGE = 0
THEN CAST (h$cte.sort_path + '/' + ORGANIZATIONS.TITLE AS NVARCHAR(MAX))
ELSE CAST (h$cte.sort_path + '/' + ORGANIZATIONS.ARABIC_TITLE AS NVARCHAR(MAX))
END sort_path
FROM
ERP.ORGANIZATIONS
INNER JOIN
ERP.ORGANIZATION_TYPES ON ORGANIZATIONS.ORGANIZATION_TYPE_ID = ORGANIZATION_TYPES.ORGANIZATION_TYPE_ID
,h$cte
WHERE
h$cte.ORGANIZATION_ID = ORGANIZATIONS.PARENT_ID
)
SELECT
h$cte.ORGANIZATION_ID,
ISNULL(h$cte.PARENT_ID, -1) AS PARENT_ID,
h$cte.TITLE ,
h$cte.ARABIC_TITLE ,
h$cte.TITLE ORGANIZATION_TYPE ,
h$cte.ARABIC_TITLE ARABIC_ORGANIZATION_TYPE ,
Level ,
ERP.EF_ORGANIZATION_ISPARENT(h$cte.ORGANIZATION_ID) AS is_parent ,
h$cte.IS_ACTIVE ,
ISNULL(ORGANIZATIONS_OWNERS.ORGANIZATION_OWNER_ID, -1) AS ORGANIZATION_OWNER_ID ,
ISNULL(ASSIGNMENTS.ASSIGNMENT_ID, -1) AS ASSIGNMENT_ID ,
HRMS.FN_GETFORMATTEDARABPEOPLENAME(ASSIGNMENTS.PERSON_ID, GETDATE()) AS OWNER_ARABIC_TITLE ,
HRMS.FN_GETFORMATTEDPEOPLENAME(ASSIGNMENTS.PERSON_ID, GETDATE()) AS OWNER_TITLE ,
ISNULL(TAKLEEF.START_DATE,ISNULL(ORGANIZATIONS_OWNERS.EFFECTIVE_START_DATE, GETDATE())) AS EFFECTIVE_START_DATE ,
ISNULL(TAKLEEF.END_DATE,ISNULL(ORGANIZATIONS_OWNERS.EFFECTIVE_END_DATE, GETDATE())) AS EFFECTIVE_END_DATE
FROM
h$cte
LEFT OUTER JOIN
HRMS.ORGANIZATIONS_OWNERS ON h$cte.ORGANIZATION_ID = ORGANIZATIONS_OWNERS.ORGANIZATION_ID
AND ORGANIZATIONS_OWNERS.EFFECTIVE_END_DATE IS NULL
LEFT OUTER JOIN
HRMS.TAKLEEF ON [h$cte].ORGANIZATION_ID = TAKLEEF.DEPARTMENT_ID
AND Takleef.IS_DEPARTMENT_OWNER = 1
AND GETDATE() BETWEEN START_DATE AND ISNULL(END_DATE, GETDATE())
LEFT OUTER JOIN
HRMS.ASSIGNMENTS ON ISNULL(TAKLEEF.ASSIGNMENT_ID, ORGANIZATIONS_OWNERS.ASSIGNMENT_ID) = ASSIGNMENTS.ASSIGNMENT_ID
ORDER BY
sort_path;

Table Spool right before insert?

What I understand about SPOOL is to store data into a temporary table so SQL Server could use it when have CTE or other usage. Does that means SPOOL should appear in the middle of my execution plan?
With the query below(I put SELECT * here to make the query smaller), the SPOOL shows up between INSERT and CONCATENATION actions in my execution plan. Just wondering what does this SPOOL do? Cause it costs about 30% in my execution plan. Wondering if I can make the plan get rid of it.
Edit: Execution Plan uploaded
WITH FXSPOT AS (
SELECT
CURRENCY1
, FXRATE
FROM
#DBNAME#.DBO.#TBL1#
WHERE
FXSPOT.DATA_DATE = '2016-10-01'
), FTP_MTD_PRE AS (
SELECT
*
FROM #DBNAME#.DBO.#TBL2#
WHERE
RP_DATA_DT = DATEADD(D, -1, CONVERT(DATE, '2016-10-01')) AND
DAY(DATEADD(D, 1, CONVERT(DATE, RP_DATA_DT))) > 1 AND
RUN_ID = 'RC01'
), PORT AS (
SELECT
*
FROM #DBNAME#.DBO.#TBL3#
), LK_ALL AS (
SELECT
FIELDNAME
, CD
, DESCRIPTION
FROM #DBNAME#.DBO.#TBL4#
), FTP_OUT AS (
SELECT
*
FROM #DBNAME#.DBO.#TBL5#
WHERE
CURR_DT = '2016-10-01' AND
RUN_ID = 'RC01'
), DEFAULT_INDEX AS (
SELECT
IDX_FORMULA
FROM #DBNAME#.DBO.#TBL6#
WHERE
INDEX_ID = 'DEFAULT'
), STEP1 AS (
SELECT
'RC01' RUN_ID
, CONVERT(DATE, '2016-10-01') CURRENT_DT
, CONVERT(DATE, '2016-10-01') RP_DATA_DT
, CASE WHEN FTP_OUT.TXN_ID IS NULL THEN '1' ELSE '0' END ERR_FLG
, PORT.TXN_ID_R_PRODCD
, PORT.TXN_ID
, PORT.SCURITY_ID
, PORT.PRODUCT_ID
, PORT.AMRT_TYP
, PORT.CUR_PMT
, PORT.CURRENCY
, PORT.DAY_COUNT
, PORT.FIX_FLT
, PORT.FSTAMRT_DT
, PORT.FST_CPN_DT
, PORT.ISSUE_DT
, PORT.MAT_DT
, PORT.NXT_RSTDT
, PORT.ORG_PAR_BAL
, PORT.ORG_PAR_BL2
, PORT.PAY_DAY
, PORT.PMT_FLG
, PORT.PMT_FREQ
, PORT.PMT_FREQ_M
, PORT.PRV_RSTDT
, PORT.RST_FRQ
, PORT.RST_FRQ_M
, PORT.SNK_DAY
, PORT.SNK_PMT
, PORT.SNK_RT
, PORT.SNK_FRQ
, PORT.SNK_FRQ_M
, PORT.SNK_P_FLG
, PORT.TENOR
, PORT.TENOR_M
, PORT.TP_ADJ1_ID
, PORT.TP_ADJ2_ID
, PORT.TP_ADJ3_ID
, PORT.TP_ADJ4_ID
, PORT.TP_ADJ5_ID
, PORT.TP_ID
, PORT.TP_INDEX_ID
, PORT.TRANSPRICE
, PORT.ASST_LIAB
, PORT.PAR_BAL
, PORT.CUR_BK_BAL
, PORT.CUR_BK_BAL * FXSPOT.FXRATE CUR_BK_BAL_DOM
, PORT.T_CUR_BK_BAL
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE T_CUR_BK_BAL_DOM
, PORT.CUR_GRS_RT
, PORT.T_UNEARN
, PORT.T_UNEARN * FXSPOT.FXRATE T_UNEARN_DOM
, PORT.T_CURBAL
, PORT.T_CURBAL * FXSPOT.FXRATE T_CURBAL_DOM
, PORT.T_POINTAMT
, PORT.T_POINTAMT * FXSPOT.FXRATE T_POINTAMT_DOM
, PORT.T_RESTBALC
, PORT.T_RESTBALC * FXSPOT.FXRATE T_RESTBALC_DOM
, PORT.G_BANKNO
, PORT.G_CSTCTR
, PORT.G_GLACCTNO
, PORT.G_GLACCTYP
, PORT.G_GLACCTINT
, PORT.T_RTTYP
, PORT.T_PMTTYP
, PORT.T_NIDPMMD
, PORT.T_CAHSSS
, PORT.R_LOBCD
, PORT.R_BRNCHCD
, PORT.R_PRODCD
, PORT.R_TYPCD
, PORT.R_HPTYPCD
, PORT.R_NAME R_NAME
, PORT.R_CUSTCODE R_CUSTCODE
, PORT.R_PRODTYP R_PRODTYP
, PORT.R_INTPLAN R_INTPLAN
, PORT.R_DEPGRP_NAME R_DEPGRP_NAME
, PORT.R_DEPID R_DEPID
, PORT.R_MISC_IND R_MISC_IND
, PORT.R_SRCTBL R_SRCTBL
, PORT.R_RESTIND R_RESTIND
, PORT.R_SECNO R_SECNO
, PORT.R_PAIDIND R_PAIDIND
, COALESCE(FTP_OUT.TP_ORIGNAL, DEFAULT_INDEX.IDX_FORMULA) TP_ORIGNAL
, FTP_OUT.TP_ADJ1 TP_ADJ1
, FTP_OUT.TP_ADJ2 TP_ADJ2
, FTP_OUT.TP_ADJ3 TP_ADJ3
, FTP_OUT.TP_ADJ4 TP_ADJ4
, FTP_OUT.TP_ADJ5 TP_ADJ5
, COALESCE(FTP_OUT.TP_FINAL, DEFAULT_INDEX.IDX_FORMULA) TP_FINAL
, FTP_OUT.DURATION DURATION
, FTP_OUT.WAL WAL
, FTP_OUT.USER_INPUT USER_INPUT
, COALESCE(FTP_OUT.TP_MODEL, 'D') TP_MODEL
, FTP_OUT.TP_CLASS TP_CLASS
, FTP_OUT.YC_DT YC_DT
, FTP_OUT.START_DT START_DT
, FTP_OUT.END_DT END_DT
, (PORT.CUR_GRS_RT - COALESCE(FTP_OUT.TP_FINAL, DEFAULT_INDEX.IDX_FORMULA)) * PORT.ASST_LIAB TR_FINAL_SPREAD
, (PORT.CUR_GRS_RT - COALESCE(FTP_OUT.TP_ORIGNAL, DEFAULT_INDEX.IDX_FORMULA)) * PORT.ASST_LIAB TR_SPREAD
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * PORT.CUR_GRS_RT / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB TR_IE_INT
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * FTP_OUT.TP_ADJ1 / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ADJ1
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * FTP_OUT.TP_ADJ2 / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ADJ2
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * FTP_OUT.TP_ADJ3 / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ADJ3
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * FTP_OUT.TP_ADJ4 / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ADJ4
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * FTP_OUT.TP_ADJ5 / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ADJ5
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * COALESCE(FTP_OUT.TP_ORIGNAL, DEFAULT_INDEX.IDX_FORMULA) / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TP_ORG
, PORT.T_CUR_BK_BAL * FXSPOT.FXRATE * COALESCE(FTP_OUT.TP_FINAL, DEFAULT_INDEX.IDX_FORMULA) / 100.0 * PORT.DAY_COUNT_VALUE * PORT.ASST_LIAB * -1 TR_IE_TRNS
, COALESCE(FTP_OUT.TP_FINAL, DEFAULT_INDEX.IDX_FORMULA) TR_TP_FINAL
, FXSPOT.FXRATE
, DAY(CONVERT(DATE, '2016-10-01')) TR_DAYS_MTD_TODAY
FROM PORT
LEFT JOIN FTP_OUT ON PORT.TXN_ID = FTP_OUT.TXN_ID
LEFT JOIN FXSPOT ON PORT.CURRENCY = FXSPOT.CURRENCY1
LEFT JOIN DEFAULT_INDEX ON 1 = 1
), STEP2 AS (
SELECT
STEP1.*
, FTP_MTD_PRE.TXN_STATUS_FLG TXN_STATUS_FLG_PRE
, CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN '0' WHEN FTP_MTD_PRE.TXN_ID_R_PRODCD IS NOT NULL THEN '1' WHEN FTP_MTD_PRE.TXN_ID_R_PRODCD IS NULL THEN '2' END TXN_STATUS_FLG
, STEP1.T_CUR_BK_BAL_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_BAL_MTD, 0) END TR_BAL_MTD
, STEP1.T_CUR_BK_BAL_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_BAL_MTD, 0) END / DAY(CONVERT(DATE, RP_DATA_DT)) TR_AVGBAL_MTD
, STEP1.T_CURBAL_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_BAL_MTD, 0) END TR_CURBAL_MTD
, STEP1.T_CURBAL_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_BAL_MTD, 0) END / DAY(CONVERT(DATE, RP_DATA_DT)) TR_AVGCURBAL_MTD
, STEP1.TR_IE_TRNS * -1 TR_FC_TRNS
, STEP1.TR_IE_INT + STEP1.TR_IE_TRNS TR_MARGIN
, STEP1.T_POINTAMT_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_POINTAMT_MTD, 0) END TR_POINTAMT_MTD
, STEP1.T_POINTAMT_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_POINTAMT_MTD, 0) END / DAY(CONVERT(DATE, RP_DATA_DT)) TR_AVGPOINTAMT_MTD
, STEP1.T_RESTBALC_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_RESTBALC_MTD, 0) END TR_RESTBALC_MTD
, STEP1.T_RESTBALC_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_RESTBALC_MTD, 0) END / DAY(CONVERT(DATE, RP_DATA_DT)) TR_AVGRESTBALC_MTD
, STEP1.T_UNEARN_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_UNEARN_MTD, 0) END TR_UNEARN_MTD
, STEP1.T_UNEARN_DOM + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_UNEARN_MTD, 0) END / DAY(CONVERT(DATE, RP_DATA_DT)) TR_AVGUNEARN_MTD
, STEP1.TR_IE_TRNS * -1 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_FCTRNS_MTD, 0) END TR_FCTRNS_MTD
, STEP1.TR_IE_TP_ADJ1 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ADJ1_MTD, 0) END TR_IE_TP_ADJ1_MTD
, STEP1.TR_IE_TP_ADJ2 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ADJ2_MTD, 0) END TR_IE_TP_ADJ2_MTD
, STEP1.TR_IE_TP_ADJ3 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ADJ3_MTD, 0) END TR_IE_TP_ADJ3_MTD
, STEP1.TR_IE_TP_ADJ4 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ADJ4_MTD, 0) END TR_IE_TP_ADJ4_MTD
, STEP1.TR_IE_TP_ADJ5 + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ADJ5_MTD, 0) END TR_IE_TP_ADJ5_MTD
, STEP1.TR_IE_TP_ORG + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IE_TP_ORG_MTD, 0) END TR_IE_TP_ORG_MTD
, STEP1.TR_IE_INT + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IEINT_MTD, 0) END TR_IEINT_MTD
, STEP1.TR_IE_TRNS + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_IETRNS_MTD, 0) END TR_IETRNS_MTD
, STEP1.TR_IE_INT + STEP1.TR_IE_TRNS + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.TR_MARGIN_MTD, 0) END TR_MARGIN_MTD
, STEP1.CUR_GRS_RT * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB W_CUR_GRS_RT
, (STEP1.CUR_GRS_RT * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB) + CASE WHEN TR_DAYS_MTD_TODAY = 1 THEN 0 ELSE ISNULL(FTP_MTD_PRE.W_CUR_GRS_RT_MTD, 0) END W_CUR_GRS_RT_MTD
, STEP1.TP_ADJ1 * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TP_ADJ1
, STEP1.TP_ADJ2 * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TP_ADJ2
, STEP1.TP_ADJ3 * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TP_ADJ3
, STEP1.TP_ADJ4 * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TP_ADJ4
, STEP1.TP_ADJ5 * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TP_ADJ5
, STEP1.TR_FINAL_SPREAD * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TR_FINAL_SPREAD
, STEP1.TP_FINAL * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TR_TP_FINAL
, STEP1.TP_ORIGNAL * STEP1.T_CUR_BK_BAL_DOM * STEP1.ASST_LIAB * -1 W_TR_TP_ORIGNAL
, FTP_MTD_PRE.W_CUR_GRS_RT_MTD P_W_CUR_GRS_RT_MTD
, FTP_MTD_PRE.W_TP_ADJ1_MTD P_W_TP_ADJ1_MTD
, FTP_MTD_PRE.W_TP_ADJ2_MTD P_W_TP_ADJ2_MTD
, FTP_MTD_PRE.W_TP_ADJ3_MTD P_W_TP_ADJ3_MTD
, FTP_MTD_PRE.W_TP_ADJ4_MTD P_W_TP_ADJ4_MTD
, FTP_MTD_PRE.W_TP_ADJ5_MTD P_W_TP_ADJ5_MTD
, FTP_MTD_PRE.W_TR_FINAL_SPREAD_MTD P_W_TR_FINAL_SPREAD_MTD
, FTP_MTD_PRE.W_TR_TP_FINAL_MTD P_W_TR_TP_FINAL_MTD
, FTP_MTD_PRE.W_TR_TP_ORIGNAL_MTD P_W_TR_TP_ORIGNAL_MTD
FROM STEP1
LEFT JOIN FTP_MTD_PRE ON STEP1.TXN_ID_R_PRODCD = FTP_MTD_PRE.TXN_ID_R_PRODCD
)
INSERT INTO R_PBB_FTP_V1225.DBO.FTP_MTD_MC (
RP_DATA_DT
, TXN_ID_R_PRODCD
, TXN_STATUS_FLG
, TXN_STATUS_PREV
, ERR_FLG
, TXN_ID
, SCURITY_ID
, PRODUCT_ID
, AMRT_TYP
, ASST_LIAB
, CUR_BK_BAL
, T_CUR_BK_BAL
, CUR_GRS_RT
, CUR_PMT
, CURRENCY
, DAY_COUNT
, FIX_FLT
, FSTAMRT_DT
, FST_CPN_DT
, ISSUE_DT
, MAT_DT
, NXT_RSTDT
, ORG_PAR_BAL
, ORG_PAR_BL2
, PAY_DAY
, PMT_FLG
, PMT_FREQ
, PMT_FREQ_M
, PRV_RSTDT
, RST_FRQ
, RST_FRQ_M
, SNK_DAY
, SNK_FRQ
, SNK_FRQ_M
, SNK_P_FLG
, SNK_PMT
, SNK_RT
, TENOR
, TENOR_M
, TP_ADJ1_ID
, TP_ADJ2_ID
, TP_ADJ3_ID
, TP_ADJ4_ID
, TP_ADJ5_ID
, TP_ID
, TP_INDEX_ID
, TRANSPRICE
, RUN_ID
, CURRENT_DT
, TP_ORIGNAL
, TP_ADJ1
, TP_ADJ2
, TP_ADJ3
, TP_ADJ4
, TP_ADJ5
, TP_FINAL
, DURATION
, WAL
, USER_INPUT
, TP_MODEL
, TP_CLASS
, YC_DT
, START_DT
, END_DT
, FXRATE
, CUR_BK_BAL_DOM
, T_CUR_BK_BAL_DOM
, TR_SPREAD
, TR_FINAL_SPREAD
, TR_TP_FINAL
, TR_IE_INT
, TR_IE_TP_ORG
, TR_IE_TP_ADJ1
, TR_IE_TP_ADJ2
, TR_IE_TP_ADJ3
, TR_IE_TP_ADJ4
, TR_IE_TP_ADJ5
, TR_IE_TRNS
, TR_MARGIN
, TR_FC_TRNS
, TR_DAYS_MTD
, TR_BAL_MTD
, TR_AVGBAL_MTD
, TR_IEINT_MTD
, TR_IE_TP_ORG_MTD
, TR_IE_TP_ADJ1_MTD
, TR_IE_TP_ADJ2_MTD
, TR_IE_TP_ADJ3_MTD
, TR_IE_TP_ADJ4_MTD
, TR_IE_TP_ADJ5_MTD
, TR_IETRNS_MTD
, TR_MARGIN_MTD
, TR_FCTRNS_MTD
, W_CUR_GRS_RT
, W_TR_TP_ORIGNAL
, W_TP_ADJ1
, W_TP_ADJ2
, W_TP_ADJ3
, W_TP_ADJ4
, W_TP_ADJ5
, W_TR_FINAL_SPREAD
, W_TR_TP_FINAL
, W_CUR_GRS_RT_MTD
, W_TR_TP_ORIGNAL_MTD
, W_TP_ADJ1_MTD
, W_TP_ADJ2_MTD
, W_TP_ADJ3_MTD
, W_TP_ADJ4_MTD
, W_TP_ADJ5_MTD
, W_TR_FINAL_SPREAD_MTD
, W_TR_TP_FINAL_MTD
, AVG_CUR_GRS_RT
, AVG_TR_TP_ORIGNAL
, AVG_TP_ADJ1
, AVG_TP_ADJ2
, AVG_TP_ADJ3
, AVG_TP_ADJ4
, AVG_TP_ADJ5
, AVG_TR_FINAL_SPREAD
, AVG_TR_TP_FINAL
, G_BANKNO
, G_CSTCTR
, G_GLACCTNO
, G_GLACCTYP
, G_GLACCTINT
, T_RTTYP
, T_PMTTYP
, T_NIDPMMD
, T_CAHSSS
, R_LOBCD
, R_BRNCHCD
, R_PRODCD
, R_TYPCD
, R_HPTYPCD
, DSC_G_BANKNO
, DSC_G_CSTCTR
, DSC_G_GLACCTNO
, DSC_G_GLACCTYP
, DSC_G_GLACCTINT
, DSC_T_RTTYP
, DSC_T_PMTTYP
, DSC_T_NIDPMMD
, DSC_T_CAHSSS
, DSC_R_LOBCD
, DSC_R_BRNCHCD
, DSC_R_PRODCD
, DSC_R_TYPCD
, DSC_R_HPTYPCD
, R_NAME
, R_CUSTCODE
, R_PRODTYP
, R_INTPLAN
, R_DEPGRP_NAME
, R_DEPID
, R_MISC_IND
, R_SRCTBL
, R_RESTIND
, R_SECNO
, R_PAIDIND
, T_UNEARN
, T_UNEARN_DOM
, TR_UNEARN_MTD
, TR_AVGUNEARN_MTD
, T_CURBAL
, T_CURBAL_DOM
, TR_CURBAL_MTD
, TR_AVGCURBAL_MTD
, T_POINTAMT
, T_POINTAMT_DOM
, TR_POINTAMT_MTD
, TR_AVGPOINTAMT_MTD
, T_RESTBALC
, T_RESTBALC_DOM
, TR_RESTBALC_MTD
, TR_AVGRESTBALC_MTD
, CURR_DT
, R_PROCESS_DT
)
SELECT
STEP2.RP_DATA_DT
, STEP2.TXN_ID_R_PRODCD
, STEP2.TXN_STATUS_FLG
, STEP2.TXN_STATUS_FLG_PRE
, STEP2.ERR_FLG
, STEP2.TXN_ID
, STEP2.SCURITY_ID
, STEP2.PRODUCT_ID
, STEP2.AMRT_TYP
, STEP2.ASST_LIAB
, STEP2.CUR_BK_BAL
, STEP2.T_CUR_BK_BAL
, STEP2.CUR_GRS_RT
, STEP2.CUR_PMT
, STEP2.CURRENCY
, STEP2.DAY_COUNT
, STEP2.FIX_FLT
, STEP2.FSTAMRT_DT
, STEP2.FST_CPN_DT
, STEP2.ISSUE_DT
, STEP2.MAT_DT
, STEP2.NXT_RSTDT
, STEP2.ORG_PAR_BAL
, STEP2.ORG_PAR_BL2
, STEP2.PAY_DAY
, STEP2.PMT_FLG
, STEP2.PMT_FREQ
, STEP2.PMT_FREQ_M
, STEP2.PRV_RSTDT
, STEP2.RST_FRQ
, STEP2.RST_FRQ_M
, STEP2.SNK_DAY
, STEP2.SNK_FRQ
, STEP2.SNK_FRQ_M
, STEP2.SNK_P_FLG
, STEP2.SNK_PMT
, STEP2.SNK_RT
, STEP2.TENOR
, STEP2.TENOR_M
, STEP2.TP_ADJ1_ID
, STEP2.TP_ADJ2_ID
, STEP2.TP_ADJ3_ID
, STEP2.TP_ADJ4_ID
, STEP2.TP_ADJ5_ID
, STEP2.TP_ID
, STEP2.TP_INDEX_ID
, STEP2.TRANSPRICE
, STEP2.RUN_ID
, STEP2.CURRENT_DT
, STEP2.TP_ORIGNAL
, STEP2.TP_ADJ1
, STEP2.TP_ADJ2
, STEP2.TP_ADJ3
, STEP2.TP_ADJ4
, STEP2.TP_ADJ5
, STEP2.TP_FINAL
, STEP2.DURATION
, STEP2.WAL
, CASE WHEN STEP2.USER_INPUT = '' THEN NULL ELSE STEP2.USER_INPUT END USER_INPUT
, CASE WHEN STEP2.TP_MODEL = '' THEN NULL ELSE STEP2.TP_MODEL END TP_MODEL
, STEP2.TP_CLASS
, STEP2.YC_DT
, STEP2.START_DT
, STEP2.END_DT
, STEP2.FXRATE
, STEP2.CUR_BK_BAL_DOM
, STEP2.T_CUR_BK_BAL_DOM
, STEP2.TR_SPREAD
, STEP2.TR_FINAL_SPREAD
, STEP2.TR_TP_FINAL
, STEP2.TR_IE_INT
, STEP2.TR_IE_TP_ORG
, STEP2.TR_IE_TP_ADJ1
, STEP2.TR_IE_TP_ADJ2
, STEP2.TR_IE_TP_ADJ3
, STEP2.TR_IE_TP_ADJ4
, STEP2.TR_IE_TP_ADJ5
, STEP2.TR_IE_TRNS
, STEP2.TR_MARGIN
, STEP2.TR_FC_TRNS
, STEP2.TR_DAYS_MTD_TODAY
, STEP2.TR_BAL_MTD
, STEP2.TR_AVGBAL_MTD
, STEP2.TR_IEINT_MTD
, STEP2.TR_IE_TP_ORG_MTD
, STEP2.TR_IE_TP_ADJ1_MTD
, STEP2.TR_IE_TP_ADJ2_MTD
, STEP2.TR_IE_TP_ADJ3_MTD
, STEP2.TR_IE_TP_ADJ4_MTD
, STEP2.TR_IE_TP_ADJ5_MTD
, STEP2.TR_IETRNS_MTD
, STEP2.TR_MARGIN_MTD
, STEP2.TR_FCTRNS_MTD
, STEP2.W_CUR_GRS_RT
, STEP2.W_TR_TP_ORIGNAL
, STEP2.W_TP_ADJ1
, STEP2.W_TP_ADJ2
, STEP2.W_TP_ADJ3
, STEP2.W_TP_ADJ4
, STEP2.W_TP_ADJ5
, STEP2.W_TR_FINAL_SPREAD
, STEP2.W_TR_TP_FINAL
, STEP2.W_CUR_GRS_RT_MTD
, STEP2.W_TR_TP_ORIGNAL + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_TP_ORIGNAL_MTD END W_TR_TP_ORIGNAL_MTD
, STEP2.W_TP_ADJ1 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ1_MTD END W_TP_ADJ1_MTD
, STEP2.W_TP_ADJ2 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ2_MTD END W_TP_ADJ2_MTD
, STEP2.W_TP_ADJ3 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ3_MTD END W_TP_ADJ3_MTD
, STEP2.W_TP_ADJ4 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ4_MTD END W_TP_ADJ4_MTD
, STEP2.W_TP_ADJ5 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ5_MTD END W_TP_ADJ5_MTD
, STEP2.W_TR_FINAL_SPREAD + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_FINAL_SPREAD_MTD END W_TR_FINAL_SPREAD_MTD
, STEP2.W_TR_TP_FINAL + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_TP_FINAL_MTD END W_TR_TP_FINAL_MTD
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE STEP2.W_CUR_GRS_RT_MTD / STEP2.TR_BAL_MTD END AVG_CUR_GRS_RT
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TR_TP_ORIGNAL + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_TP_ORIGNAL_MTD END) / STEP2.TR_BAL_MTD END AVG_TR_TP_ORIGNAL
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TP_ADJ1 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ1_MTD END) / STEP2.TR_BAL_MTD END AVG_TP_ADJ1
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TP_ADJ2 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ2_MTD END) / STEP2.TR_BAL_MTD END AVG_TP_ADJ2
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TP_ADJ3 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ3_MTD END) / STEP2.TR_BAL_MTD END AVG_TP_ADJ3
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TP_ADJ4 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ4_MTD END) / STEP2.TR_BAL_MTD END AVG_TP_ADJ4
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TP_ADJ5 + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TP_ADJ5_MTD END) / STEP2.TR_BAL_MTD END AVG_TP_ADJ5
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TR_FINAL_SPREAD + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_FINAL_SPREAD_MTD END) / STEP2.TR_BAL_MTD END AVG_TR_FINAL_SPREAD
, CASE WHEN STEP2.TR_BAL_MTD = 0 THEN 0 ELSE (STEP2.W_TR_TP_FINAL + CASE WHEN STEP2.TXN_STATUS_FLG = 0 THEN 0 ELSE STEP2.P_W_TR_TP_FINAL_MTD END) / STEP2.TR_BAL_MTD END AVG_TR_TP_FINAL
, STEP2.G_BANKNO
, STEP2.G_CSTCTR
, STEP2.G_GLACCTNO
, STEP2.G_GLACCTYP
, STEP2.G_GLACCTINT
, STEP2.T_RTTYP
, STEP2.T_PMTTYP
, STEP2.T_NIDPMMD
, STEP2.T_CAHSSS
, STEP2.R_LOBCD
, STEP2.R_BRNCHCD
, STEP2.R_PRODCD
, STEP2.R_TYPCD
, STEP2.R_HPTYPCD
, D1.DESCRIPTION DSC_G_BANKNO
, D2.DESCRIPTION DSC_G_CSTCTR
, D3.DESCRIPTION DSC_G_GLACCTNO
, D4.DESCRIPTION DSC_G_GLACCTYP
, D5.DESCRIPTION DSC_G_GLACCTINT
, D6.DESCRIPTION DSC_T_RTTYP
, D7.DESCRIPTION DSC_T_PMTTYP
, D8.DESCRIPTION DSC_T_NIDPMMD
, D9.DESCRIPTION DSC_T_CAHSSS
, D10.DESCRIPTION DSC_R_LOBCD
, D11.DESCRIPTION DSC_R_BRNCHCD
, D12.DESCRIPTION DSC_R_PRODCD
, D13.DESCRIPTION DSC_R_TYPCD
, D14.DESCRIPTION DSC_R_HPTYPCD
, STEP2.R_NAME
, STEP2.R_CUSTCODE
, STEP2.R_PRODTYP
, STEP2.R_INTPLAN
, STEP2.R_DEPGRP_NAME
, STEP2.R_DEPID
, STEP2.R_MISC_IND
, STEP2.R_SRCTBL
, STEP2.R_RESTIND
, STEP2.R_SECNO
, STEP2.R_PAIDIND
, STEP2.T_UNEARN
, STEP2.T_UNEARN_DOM
, STEP2.TR_UNEARN_MTD
, STEP2.TR_AVGUNEARN_MTD
, STEP2.T_CURBAL
, STEP2.T_CURBAL_DOM
, STEP2.TR_CURBAL_MTD
, STEP2.TR_AVGCURBAL_MTD
, STEP2.T_POINTAMT
, STEP2.T_POINTAMT_DOM
, STEP2.TR_POINTAMT_MTD
, STEP2.TR_AVGPOINTAMT_MTD
, STEP2.T_RESTBALC
, STEP2.T_RESTBALC_DOM
, STEP2.TR_RESTBALC_MTD
, STEP2.TR_AVGRESTBALC_MTD
, RP_DATA_DT CURR_DT
, CONVERT(DATE, GETDATE()) R_PROCESS_DT
FROM STEP2
LEFT JOIN LK_ALL D1 ON D1.FIELDNAME = 'G_BANKNO' AND STEP2.G_BANKNO = D1.CD
LEFT JOIN LK_ALL D2 ON D2.FIELDNAME = 'G_CSTCTR' AND STEP2.G_CSTCTR = D2.CD
LEFT JOIN LK_ALL D3 ON D3.FIELDNAME = 'G_GLACCTNO' AND STEP2.G_GLACCTNO = D3.CD
LEFT JOIN LK_ALL D4 ON D4.FIELDNAME = 'G_GLACCTYP' AND STEP2.G_GLACCTYP = D4.CD
LEFT JOIN LK_ALL D5 ON D5.FIELDNAME = 'G_GLACCTINT' AND STEP2.G_GLACCTINT = D5.CD
LEFT JOIN LK_ALL D6 ON D6.FIELDNAME = 'T_RTTYP' AND STEP2.T_RTTYP = D6.CD
LEFT JOIN LK_ALL D7 ON D7.FIELDNAME = 'T_PMTTYP' AND STEP2.T_PMTTYP = D7.CD
LEFT JOIN LK_ALL D8 ON D8.FIELDNAME = 'T_NIDPMMD' AND STEP2.T_NIDPMMD = D8.CD
LEFT JOIN LK_ALL D9 ON D9.FIELDNAME = 'T_CAHSSS' AND STEP2.T_CAHSSS = D9.CD
LEFT JOIN LK_ALL D10 ON D10.FIELDNAME = 'R_LOBCD' AND STEP2.R_LOBCD = D10.CD
LEFT JOIN LK_ALL D11 ON D11.FIELDNAME = 'R_BRNCHCD' AND STEP2.R_BRNCHCD = D11.CD
LEFT JOIN LK_ALL D12 ON D12.FIELDNAME = 'R_PRODCD' AND STEP2.R_PRODCD = D12.CD
LEFT JOIN LK_ALL D13 ON D13.FIELDNAME = 'R_TYPCD' AND STEP2.R_TYPCD = D13.CD
LEFT JOIN LK_ALL D14 ON D14.FIELDNAME = 'R_HPTYPCD' AND STEP2.R_HPTYPCD = D14.CD
UNION ALL
SELECT
'2016-10-01' RP_DATA_DT
, FTP_MTD_PRE.TXN_ID_R_PRODCD
, '3' TXN_STATUS_FLG
, FTP_MTD_PRE.TXN_STATUS_FLG
, FTP_MTD_PRE.ERR_FLG
, FTP_MTD_PRE.T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ERE NOT EXISTS (SELECT 1 FROM PORT WHERE FTP_MTD_PRE.TXN_ID_R_PRODCD = PORT.TXN_ID_R_PRODCD)
Soool is copy of data in temp db .
Query have cte used to create new cte so execution logic is getting complicated to solve the problem sql server need to create interim result set the same is visible in query plan as spool.
https://technet.microsoft.com/en-us/library/ms181032(v=sql.105).aspx
IMHO , there is no point in CTE where there is no filter or calculation
for example LK_ALL,you can directly use #DBNAME#.DBO.#TBL4# where req. it may or may not improve performance,but at least it reduce number of lines.
It is really tough to debug, whole query.
but see here instead of so many left join(BTW,if you can use inner join)
you can rewrite your query like this,
FROM STEP2
Inner/LEFT JOIN LK_ALL D1 ON (STEP2.G_BANKNO = D1.CD AND D1.FIELDNAME = 'G_BANKNO')
or (D2.FIELDNAME = 'G_CSTCTR' AND STEP2.G_CSTCTR = D2.CD )
or (D3.FIELDNAME = 'G_GLACCTNO' AND STEP2.G_GLACCTNO = D3.CD )
or (D4.FIELDNAME = 'G_GLACCTYP' AND STEP2.G_GLACCTYP = D4.CD )
or (D5.FIELDNAME = 'G_GLACCTINT' AND STEP2.G_GLACCTINT = D5.CD )
or (D6.FIELDNAME = 'T_RTTYP' AND STEP2.T_RTTYP = D6.CD )
or (D7.FIELDNAME = 'T_PMTTYP' AND STEP2.T_PMTTYP = D7.CD )
or (D8.FIELDNAME = 'T_NIDPMMD' AND STEP2.T_NIDPMMD = D8.CD )
or (D9.FIELDNAME = 'T_CAHSSS' AND STEP2.T_CAHSSS = D9.CD )
or ( D10.FIELDNAME = 'R_LOBCD' AND STEP2.R_LOBCD = D10.CD )
or ( D11.FIELDNAME = 'R_BRNCHCD' AND STEP2.R_BRNCHCD = D11.CD )
or ( D12.FIELDNAME = 'R_PRODCD' AND STEP2.R_PRODCD = D12.CD )
or ( D13.FIELDNAME = 'R_TYPCD' AND STEP2.R_TYPCD = D13.CD )
or ( D14.FIELDNAME = 'R_HPTYPCD' AND STEP2.R_HPTYPCD = D14.CD )
I hope those hard coded parameter are dynamic in real life
Also you can do like,
declare #From date= dateadd(day,-1,'2016-10-01')
declare #To int= DAY(DATEADD(D, 1, CONVERT(DATE, RP_DATA_DT)))
for millions of records temp table is better than CTE.
Also you can comment part of query to see the performance.

How to Improve SQL readability and Performance?

I have the following View:
So the question is,How to Improve SQL readability of this query?
SELECT t1.Id ,
t1.HeaderRef ,
t1.PartRef ,
t1.SLRef ,
t1.DL ,
t1.DL2 ,
t1.DL3 ,
t1.DL4 ,
t1.DL5 ,
t1.DL6 ,
t1.DL7 ,
t1.ItemRef ,
t1.CalItemRef ,
t1.RowNum ,
t1.UnitType ,
t1.UnitTypeTitle ,
t1.UnitRef ,
t1.Ratio ,
t1.Value ,
t1.MasterValue ,
t1.ItemDate ,
t1.Descript ,
t1.Year ,
t1.BranchRef ,
t1.StockRef ,
t1.OpositStockRef ,
t1.DocTypeRef ,
t1.BaseDocTypeRef ,
t1.Creator ,
t1.Confirmer ,
t1.Num ,
t1.State ,
t1.DocDate ,
t1.FCRef ,
t1.FCTitle ,
t1.PartTitle ,
t1.PartCode ,
t1.SLCode ,
t1.DL1Code ,
t1.DL2Code ,
t1.DL3Code ,
t1.DL4Code ,
t1.DL5Code ,
t1.DL6Code ,
t1.DL7Code ,
t1.UnitTitle ,
t1.PartUnitTitle ,
( ( AVG(t1.RealPrice) + SUM(t1.CorrectPrice) ) / t1.Value ) AS CorrectRate ,
AVG(t1.RealPrice) + SUM(t1.CorrectPrice) AS CorrectPrice ,
MAX(t1.CorrectAccDocHeaderRef) AS CorrectAccDocHeaderRef ,
1 AS CorrectCreator ,
1 AS CorrectConfirmer ,
MAX(t1.CorrectCreateDate) AS CorrectCreateDate ,
GETDATE() AS CorrectConfirmDate ,
CorrectFCRate = ( SELECT MAX(rr.FCRate)
FROM Stc.StcDocRate AS rr
WHERE rr.ItemRef = t1.Id
AND rr.PriceType = '2'
AND CreateDate = MAX(t1.CorrectCreateDate)
) ,
CorrectFCVal = ( SELECT MAX(rr.FCVal)
FROM Stc.StcDocRate AS rr
WHERE rr.ItemRef = t1.Id
AND rr.PriceType = '2'
AND CreateDate = MAX(t1.CorrectCreateDate)
),
CorrectDescript = ( SELECT MAX(Descript)
FROM Stc.StcDocRate AS rr
WHERE rr.ItemRef = t1.Id
AND rr.PriceType = '2'
AND CreateDate = MAX(t1.CorrectCreateDate)
) ,
AVG(t1.RealPrice) / t1.Value AS RealRate ,
AVG(t1.RealPrice) AS RealPrice ,
MAX(t1.RealAccDocHeaderRef) AS RealAccDocHeaderRef ,
1 AS RealCreator ,
1 AS RealConfirmer ,
GETDATE() AS RealCreateDate ,
GETDATE() AS RealConfirmDate ,
AVG(t1.RealFCRate) AS RealFCRate ,
AVG(t1.RealFCVal) AS RealFCVal ,
AVG(t1.CaledPrice) / t1.Value AS CaledRate ,
AVG(t1.CaledPrice) AS CaledPrice ,
MAX(t1.CaledAccDocHeaderRef) AS CaledAccDocHeaderRef ,
1 AS CaledCreator ,
1 AS CaledConfirmer ,
GETDATE() AS CaledCreateDate ,
GETDATE() AS CaledConfirmDate ,
AVG(t1.CaledFCRate) AS CaledFCRate ,
AVG(t1.CaledFCVal) AS CaledFCVal ,
t1.ItemNum ,
t1.BasePartCode ,
t1.BasePartTitle ,
t1.DlRefHeader ,
t1.SLRefHeader,
t1.ProductionValue ,
t1.FormulaRef ,
t1.StcDocReqRef
FROM ( SELECT item.Id ,
item.HeaderRef ,
item.PartRef ,
item.SLRef ,
item.DL ,
item.DL2 ,
item.DL3 ,
item.DL4 ,
item.DL5 ,
item.DL6 ,
item.DL7 ,
item.ItemRef ,
item.CalItemRef ,
item.RowNum ,
item.UnitType ,
UnitTypeTitle = CASE item.UnitType
WHEN '1' THEN N'اصلی'
WHEN '2' THEN N'فرعی'
END ,
item.UnitRef ,
item.Ratio ,
item.Value ,
item.MasterValue ,
item.ItemDate ,
item.Descript ,
item.StcDocReqRef ,
item.Year ,
item.BranchRef ,
item.StockRef ,
item.OpositStockRef ,
item.DocTypeRef ,
item.BaseDocTypeRef ,
item.Creator ,
item.Confirmer ,
item.Num ,
item.State ,
item.DocDate ,
item.FCRef ,
fc.Title AS FCTitle ,
item.ProductionValue ,
item.FormulaRef ,
p.Title AS PartTitle ,
p.Code AS PartCode ,
sl.SLCode AS SLCode ,
dl1.DLCode AS DL1Code ,
dl2.DLCode AS DL2Code ,
dl3.DLCode AS DL3Code ,
dl4.DLCode AS DL4Code ,
dl5.DLCode AS DL5Code ,
dl6.DLCode AS DL6Code ,
dl7.DLCode AS DL7Code ,
pu.Title AS UnitTitle ,
puslave.Title AS PartUnitTitle ,
CorrectRate.Rate AS CorrectRate ,
CorrectRate.Price AS CorrectPrice ,
CorrectRate.AccDocHeaderRef AS CorrectAccDocHeaderRef ,
CorrectRate.Creator AS CorrectCreator ,
CorrectRate.Confirmer AS CorrectConfirmer ,
CorrectRate.CreateDate AS CorrectCreateDate ,
CorrectRate.ConfirmDate AS CorrectConfirmDate ,
CorrectRate.FCRate AS CorrectFCRate ,
CorrectRate.FCVal AS CorrectFCVal ,
CorrectRate.Descript AS CorrectDescript ,
realRate.Rate RealRate ,
realRate.Price RealPrice ,
realRate.AccDocHeaderRef AS RealAccDocHeaderRef ,
realRate.Creator AS RealCreator ,
realRate.Confirmer AS RealConfirmer ,
realRate.CreateDate AS RealCreateDate ,
realRate.ConfirmDate AS RealConfirmDate ,
realRate.FCRate AS RealFCRate ,
realRate.FCVal AS RealFCVal ,
CaledRate.Rate AS CaledRate ,
CaledRate.Price AS CaledPrice ,
CaledRate.AccDocHeaderRef AS CaledAccDocHeaderRef ,
CaledRate.Creator AS CaledCreator ,
CaledRate.Confirmer AS CaledConfirmer ,
CaledRate.CreateDate AS CaledCreateDate ,
CaledRate.ConfirmDate AS CaledConfirmDate ,
CaledRate.FCRate AS CaledFCRate ,
CaledRate.FCVal AS CaledFCVal ,
ItemNum = CASE header.BaseDocTypeRef
WHEN 2000 THEN refReqItem.Num
WHEN 2002 THEN refOrderItem.Num
WHEN 2003 THEN refFactItem.Num
WHEN 2004 THEN refRetFactItem.Num
WHEN 2010 THEN cmrPostItem.Num
WHEN 2012 THEN cmrRet.Num
WHEN 2016 THEN header.ProductionNum
ELSE refItem.Num
END ,
refPart.Code AS BasePartCode ,
refPart.Title AS BasePartTitle ,
header.DLRef AS DlRefHeader ,
header.SLRef AS SLRefHeader
FROM Stc.StcDocItem AS item
INNER JOIN Stc.Part AS p ON p.Id = item.PartRef
LEFT OUTER JOIN Acc.SL AS sl ON sl.Id = item.SLRef
LEFT OUTER JOIN Acc.DL AS dl1 ON dl1.Id = item.DL
LEFT OUTER JOIN Acc.DL AS dl2 ON dl2.Id = item.DL2
LEFT OUTER JOIN Acc.DL AS dl3 ON dl3.Id = item.DL3
LEFT OUTER JOIN Acc.DL AS dl4 ON dl4.Id = item.DL4
LEFT OUTER JOIN Acc.DL AS dl5 ON dl5.Id = item.DL5
LEFT OUTER JOIN Acc.DL AS dl6 ON dl6.Id = item.DL6
LEFT OUTER JOIN Acc.DL AS dl7 ON dl7.Id = item.DL7
LEFT OUTER JOIN Acc.FC AS fc ON fc.Id = item.FCRef
LEFT OUTER JOIN Stc.PartUnit AS pu ON pu.Id = item.UnitRef
LEFT OUTER JOIN Stc.PartUnit AS puslave ON puslave.Id = p.UnitRef
LEFT OUTER JOIN Stc.StcDocRate AS realRate ON realRate.ItemRef = item.Id
AND realRate.PriceType = '1'
LEFT OUTER JOIN Stc.StcDocRate AS CorrectRate ON CorrectRate.ItemRef = item.Id
AND CorrectRate.PriceType = '2'
LEFT OUTER JOIN Stc.StcDocRate AS CaledRate ON CaledRate.ItemRef = item.Id
AND CaledRate.PriceType = '3'
LEFT OUTER JOIN Stc.StcDocItem AS refItem ON refItem.Id = item.ItemRef
LEFT OUTER JOIN Stc.Part AS refPart ON refItem.PartRef = refPart.Id
LEFT OUTER JOIN Stc.StcDocReqItem AS refReqItem ON refReqItem.Id = item.ItemRef
LEFT OUTER JOIN Sle.SleDocOrderItem AS refOrderItem ON refOrderItem.Id = item.ItemRef
LEFT OUTER JOIN Sle.SleDocFactItem AS refFactItem ON refFactItem.Id = item.ItemRef
LEFT OUTER JOIN Sle.SleDocRetFactItem AS refRetFactItem ON refRetFactItem.Id = item.ItemRef
LEFT OUTER JOIN CMR.CMRIntSheetPostItem AS cmrPostItem ON cmrPostItem.Id = item.ItemRef
LEFT OUTER JOIN CMR.CMRIntReturnPartNonConformingItem
AS cmrRet ON cmrRet.Id = item.ItemRef
LEFT OUTER JOIN Stc.StcDocHeader AS header ON header.Id = item.HeaderRef
) AS t1
Readability of this query is pretty bad. In particular, i had problem to understand.
I would like some feedback how to improve performance and Readability for this case?
1. readability
if you have to get one output select with all this columns, your query is well formed enough
if you can decompose your qry, so split it into smaller logical (or semantically connected) blocks
use views for pivoted output - for example instead of 8x Acc.SL left join create view with pivoted data
use functions or views to remove case statement or subqueries
separate agregations and other data (it seems in your qry is missing group by statement)
2. performance
get query plan
rewrite your query to use existing indexes or add missing indexes
force joins order if it's necessary

Combining NOT EXISTS with INSERT ... SELECT

The following code inserts a new row into a table based on a value in another row but it also allows duplicate data. I want to use NOT EXISTS so that if there is already a row with that value then it won't insert another one, but not sure how to integrate this.
INSERT INTO [Grading].[dbo].[tblObservations]
([FormID]
,[Data]
,[UserID]
,[DateOfObservation]
,[Final]
,[ValidTo]
,[ID_Grading]
,[ID_ObservationKind]
,[Created]
,[Modified]
,[RowVersion])
SELECT [FormID]
,'0'
,[UserID]
,[DateOfObservation]
,[Final]
,[ValidTo]
,[ID_Grading]
,40
,[Created]
,[Modified]
,[RowVersion]
FROM [Grading].[dbo].[tblObservations]
WHERE [ID_ObservationKind] = 39 AND [Data] = 'No' AND [Final] = 1
Any help appreciated.
Try this one -
USE [Grading]
INSERT INTO [dbo].[tblObservations]
(
FormID
, Data
, UserID
, DateOfObservation
, Final
, ValidTo
, ID_Grading
, ID_ObservationKind
, Created
, Modified
, [RowVersion]
)
SELECT
t.FormID
, '0'
, t.UserID
, t.DateOfObservation
, t.Final
, t.ValidTo
, t.ID_Grading
, 40
, t.Created
, t.Modified
, t.[RowVersion]
FROM dbo.tblObservations t
LEFT JOIN dbo.tblObservations t2 ON
t.FormID = t2.FormID
AND t2.Data = '0'
AND t.UserID = t2.UserID
AND t.DateOfObservation = t2.DateOfObservation
AND t.Final = t2.Final
AND t.ValidTo = t2.ValidTo
AND t.ID_Grading = t2.ID_Grading
AND t2.ID_ObservationKind = 40
AND t.Created = t2.Created
AND t.Modified = t2.Modified
AND t.[RowVersion] = t2.[RowVersion]
WHERE t.ID_ObservationKind = 39
AND t.Data = 'No'
AND t.Final = 1
AND t2.FormID IS NULL
Or try this -
INSERT INTO [dbo].[tblObservations]
(
FormID
, Data
, UserID
, DateOfObservation
, Final
, ValidTo
, ID_Grading
, ID_ObservationKind
, Created
, Modified
, [RowVersion]
)
SELECT
t.FormID
, '0'
, t.UserID
, t.DateOfObservation
, t.Final
, t.ValidTo
, t.ID_Grading
, 40
, t.Created
, t.Modified
, t.[RowVersion]
FROM dbo.tblObservations t
WHERE t.ID_ObservationKind = 39
AND t.Data = 'No'
AND t.Final = 1
AND NOT EXISTS(
SELECT 1
FROM dbo.tblObservations t2
WHERE t2.ID_ObservationKind = 39
AND t2.Data = 'No'
AND t2.Final = 1
)
You can try
IF NOT EXISTS
(
SELECT 1
FROM [Grading].[dbo].[tblObservations]
WHERE [ID_ObservationKind] = 39 AND [Data] = 'No' AND [Final] = 1
)
BEGIN
-- Insert script
END
You're looking to do a "merge" or "upsert" in SQL. Depending on your database, there are a number of ways to do this. If you are using MySQL, you'll want to use it's INSERT... ON DUPLICATE KEY UPDATE syntax.

how to fix sql case syntax

work on sql-server-2005
SELECT A.specific_customization_id ,
A.customization_id ,
A.customization_value ,
A.customization_price ,
A.customization_cost ,
A.customization_code ,
A.customization_check ,
A.sort_order ,
A.option_code ,
A.product_id ,
A.image_1 ,
A.image_2 ,
A.MainProductID ,
A.customization_product_id ,
A.inactive ,
A.customization_description ,
A.customization_select ,
A.UOM ,
A.allow_recur ,
auto_reorder = CASE A.MainProductID --it's an int type column
WHEN NULL THEN A.allow_recur
ELSE ( SELECT allow_recur
FROM wc_product
WHERE product_id = A.MainProductID
)
END
FROM dbo.wc_product_specific A
WHERE A.product_id = 1133
Using the above query I want to set auto_reorder column value .want to set two login
When My MainProductID column is null I want to set allow_recur column value
When it’s not null I want to set another table column value
My logic 2) works fine ,fail to understand why does 1) not work? Help me to fix the problem?
If have any query plz ask thanks in advance.
Does this work:?
SELECT A.specific_customization_id ,
A.customization_id ,
A.customization_value ,
A.customization_price ,
A.customization_cost ,
A.customization_code ,
A.customization_check ,
A.sort_order ,
A.option_code ,
A.product_id ,
A.image_1 ,
A.image_2 ,
A.MainProductID ,
A.customization_product_id ,
A.inactive ,
A.customization_description ,
A.customization_select ,
A.UOM ,
A.allow_recur ,
A.auto_reorder = CASE --it's an int type column
WHEN A.MainProductID IS NULL THEN A.allow_recur
ELSE B.allow_recur
END
FROM dbo.wc_product_specific A
left outer join wc_product B on B.product_id = A.MainProductID
WHERE A.product_id = 1133

Resources