Conversion error while converting varchar to smallint - sql

Main Qualification : Varchar(20)
Qualification_Title: Varchar(100)
Query:
select distinct Main_Qualification,
Main_Qualification + ' '+ Qualification_Title As Main_Qual_Title
from dbo.IM_EN_Main_Qualifcation_with_title_vw
where College_Year = #College_Year
and Qualification_Title not Like '%CANX%'
order by Main_Qualification + ' '+ Qualification_Title
when I execute it I am getting error:
Conversion failed when converting the varchar value '20PA' to datatype smallint
dbo.IM_EN_Main_Qualifcation_with_title_vw:
SELECT dbo.IM_EN_Main_Qualification_vw.College_Year, dbo.IM_EN_Main_Qualification_vw.Learner_ID,
dbo.IM_EN_Main_Qualification_vw.Main_Qualification_Code,
dbo.IM_EN_Main_Qualification_vw.IS_AS_Level_Umbrella,
dbo.IM_EN_Main_Qualification_vw.IS_A2_Level_Umbrella,
dbo.IM_EN_Main_Qualification_vw.Main_Qualification,
dbo.IM_LU_Qualifications_vw.Qualification_Title,
dbo.IM_LU_Qualifications_vw.Qualification_Mgmnt_Code_1,
dbo.IM_LU_Qualifications_vw.Section
,dbo.IM_LU_Qualifications_vw.Qualification_Mgmnt_Code_2
,dbo.IM_EN_Main_Qualification_vw.Code
FROM dbo.IM_EN_Main_Qualification_vw INNER JOIN
dbo.IM_LU_Qualifications_vw ON
dbo.IM_LU_Qualifications_vw.Qualification_Code = dbo.IM_EN_Main_Qualification_vw.Main_Qualification_Code AND
dbo.IM_LU_Qualifications_vw.Qualification_Year = dbo.IM_EN_Main_Qualification_vw.College_Year
[dbo].[IM_EN_Main_Qualification_vw]( we are getting Main_Qualification from this view):
SELECT e.College_Year,
e.Learner_ID,
a.Code AS Main_Qualification_Code,
MAX(b.IS_AS_Level_Umbrella) AS IS_AS_Level_Umbrella,
MAX(b.IS_A2_Level_Umbrella) AS IS_A2_Level_Umbrella,
-- Not took MAX belkow because there were two people doing both AS and A2 Levels.
-- This will give them AS Level as Main Qualification.
MAX(CASE WHEN b.IS_AS_Level_Umbrella = 'Yes' THEN 'AS Level'
WHEN b.IS_A2_Level_Umbrella = 'Yes' THEN 'A2 Level'
ELSE a.Code END) AS Main_Qualification
,a.Code
FROM IM_EN_ENROLMENTS_VW e
INNER JOIN (
-- Join to the query that gets the qual with the maximum GLH
SELECT A.COLLEGE_YEAR,
A.LEARNER_ID,
MAX(A.CODE) AS CODE,
A.GLH
FROM (-- Get GKH of all Quals and join this to highest
-- GLH the student has beteewn all Quals
SELECT COLLEGE_YEAR,
LEARNER_ID,
CODE,
SUM(GLH) AS GLH
FROM DBO.IM_EN_ENROLMENTS_VW
WHERE (TYPE_OF_RECORD = 'Q')
AND (QUALIFICATION_MGMNT_CODE_1 NOT IN ('KS','TUT'))
AND (QUALIFICATION_MGMNT_CODE_3 NOT IN ('AD'))
AND (Code NOT LIKE ('%/N%'))
AND (Completion_Stat_Q19 <> '4')
GROUP BY COLLEGE_YEAR,LEARNER_ID,CODE) AS A
INNER JOIN (
-- Get the MAX GLH of all Quals
SELECT COLLEGE_YEAR,
LEARNER_ID,
MAX(GLH) AS MAXGLH
FROM (
-- Get GKH of all Quals
SELECT COLLEGE_YEAR,
LEARNER_ID,
CODE,
SUM(GLH) AS GLH
FROM DBO.IM_EN_ENROLMENTS_VW
WHERE (TYPE_OF_RECORD = 'Q')
AND (QUALIFICATION_MGMNT_CODE_1 NOT IN ('KS','TUT'))
AND (QUALIFICATION_MGMNT_CODE_3 NOT IN ('AD'))
AND (Code NOT LIKE ('%/N%'))
AND (Completion_Stat_Q19 <> '4')
GROUP BY COLLEGE_YEAR,LEARNER_ID,CODE) AS V
GROUP BY COLLEGE_YEAR,LEARNER_ID) AS B
ON A.COLLEGE_YEAR = B.COLLEGE_YEAR
AND A.LEARNER_ID = B.LEARNER_ID
AND A.GLH = B.MAXGLH
AND A.COLLEGE_YEAR = B.COLLEGE_YEAR
group by A.COLLEGE_YEAR,
A.LEARNER_ID,
A.GLH) AS a ON e.College_year = a.College_year AND e.Learner_ID = a.Learner_ID
LEFT JOIN (
-- Get AS and A2 Level Learners
SELECT College_Year,
Learner_Id,
Code,
dbo.IS_AS_Umbrella(College_Year, Code) AS IS_AS_Level_Umbrella,
dbo.IS_A2_Umbrella(College_Year, Code) AS IS_A2_Level_Umbrella
FROM IM_EN_ENROLMENTS_VW
WHERE (dbo.IS_AS_Umbrella(College_Year, Code) = 'Yes' OR dbo.IS_A2_Umbrella(College_Year, Code) = 'Yes')
AND Type_Of_Record = 'Q') AS b ON e.College_Year = b.College_year
AND e.Learner_ID = b.Learner_ID
GROUP BY
e.College_Year,
e.Learner_ID,
a.Code
IM_LU_Qualifications_vw(getting Qualification_Title from here):
SELECT RTRIM(dbo.PRPHProvisionHeader.PRPH_Code) AS Qualification_Code,
CASE WHEN LEFT(PRPH_Code, 5) = 'S1500' OR PRPH_Code LIKE '15%' THEN 'Yes' ELSE 'No' END AS Is_AS_level,
RTRIM(dbo.PRPIProvisionInstance.PRPI_Title) AS Qualification_Title,
------------------------------
RTRIM(PRIL_Title) as Course_funding_Title,
PRPIProvisionInstance.PRPI_Status,
------------------------------
dbo.PRILILR.PRIL_Year AS Qualification_Year,
RTRIM(dbo.PRPHProvisionHeader.PRPH_ML1) AS Qualification_Mgmnt_Code_1,
dbo.IM_LU_Departments_vw.Department,
RTRIM(dbo.PRPHProvisionHeader.PRPH_ML2) AS Qualification_Mgmnt_Code_2,
CASE WHEN RTRIM(dbo.PRPIProvisionInstance.PRPI_Available_Enr) = 0 THEN 'N' ELSE 'Y' END AS Available,
dbo.IM_LU_Sections_vw.Section,
RTRIM(dbo.PRPHProvisionHeader.PRPH_ML3) AS Qualification_Mgmnt_Code_3,
RTRIM(dbo.PRPIProvisionInstance.PRPI_FT_PT) AS Qualification_FT_PT,
ISNULL(RTRIM(dbo.PRCOCoordinators.PRCO_Tutor), '') AS Coordinator_Code,
ISNULL(PRFSFeesTuition.PRFS_Fee_Amount, 0) AS Tuition_Fees,
/********* TUI24+FC ************ */
ISNULL(FullCost_24plus.PRFS_Fee_Amount, 0) AS FullCost_24plus_Fees,
---------------
ISNULL(PRFSFeesUniform.PRFS_Fee_Amount, 0) AS Uniform_Fees,
ISNULL(PRFSFeesKit.PRFS_Fee_Amount, 0) AS Kit,
--------------
ISNULL(PRFSFeesMaterials.PRFS_Fee_Amount, 0) AS Material_Fees,
------------------------Full Cost Material_Fees-----------------------------------------------------------
ISNULL(FullCostMaterialsFees.PRFS_Fee_Amount, 0) AS FullCost_Material_Fees,
/********* CRB ************ */
ISNULL(CRB_Fees.PRFS_Fee_Amount, 0) AS CRB,
----------------------------------------------------------------------------------------------------------
ISNULL(PRFSFeesExam.PRFS_Fee_Amount, 0) AS Exam_Fees,
ISNULL(PRFSFeesTrainingCredit.PRFS_Fee_Amount, 0) AS Training_Credit_TF,
ISNULL(PRFSFeesUserFee5.PRFS_Fee_Amount, 0) AS Police_Check_Fees,
ISNULL(PRFSFeesOverseas.PRFS_Fee_Amount, 0) AS Overseas_Fees,
RTRIM(ISNULL(dbo.PRTTTutors.PRTT_Tutor, '')) AS Tutor,
dbo.PERSstaff.PERS_Forename AS Course_Leader_Forename,
dbo.PERSstaff.PERS_Surname AS Course_Leader_Surname,
RTRIM(dbo.PERSstaff.PERS_Department_ML) AS Tutor_Department,
IM_LU_Departments_vw.Department AS Tutor_Department_Description,
dbo.PRPIProvisionInstance.PRPI_GLH_A32 AS Qualification_GLH,
-------------------- Columns swapped around ------------
dbo.PRILILR.PRIL_Hours_per_Week AS GLH_per_week,
dbo.PRILILR.PRIL_Annual_End_Date As Annual_End_Date,
dbo.PRILILR.PRIL_Annual_GLH AS Annual_GLH,
--dbo.PRPIProvisionInstance.PRPI_Hours_per_Week AS GLH_per_week,
--------------------------------------------------------------
dbo.PRPIProvisionInstance.PRPI_Length_Weeks AS Weeks_in_year,
dbo.PRPIProvisionInstance.PRPI_Start_Date_A27 AS Qualification_Start_Date,
dbo.PRPIProvisionInstance.PRPI_Exp_End_Date_A28 AS Qualification_End_Date,
dbo.PRILILR.PRIL_Annual_Start_Date as Annual_Start_Date,
-------------------- Columns swapped around ------------
--dbo.PRILILR.PRIL_Aim_A09 AS Qual_Aim,
dbo.PRPIProvisionInstance.PRPI_Aim AS Qual_Aim,
dbo.PRPIProvisionInstance.PRPI_Title AS Aim_Title,
--+++++++++++++++++++++++++++++++++++
------------------- Columns swapped around ------------
ISNULL(AV.FullLevel2Percent, 0) AS Full_Level2_Percentage,
ISNULL(AV.FullLevel3Percent, 0) AS Full_Level3_Percentage,
--ISNULL(dbo.LAAV_ALL_VALUES.LEVEL2_PERCENTAGE, 0) AS Full_Level2_Percentage,
--ISNULL(dbo.LAAV_ALL_VALUES.LEVEL3_PERCENTAGE, 0) AS Full_Level3_Percentage,
-------------------- Columns swapped around ------------
[dbo].[Core_LARS_LearningDelivery].NotionalNVQLevel AS NVQLevel,
[dbo].[Core_LARS_LearningDelivery].EntrySubLevel as Entry_SubLevel,
[dbo].[Core_LARS_LearningDelivery].AwardOrgCode AS Awarding_Body,
-- dbo.LAIM_AIMS.NOTIONAL_NVQ_LEVEL_CODE AS NVQLevel,
-- dbo.LAIM_AIMS.AWARDING_ORGANISATION AS Awarding_Body,
--£££££££££££££££
dbo.PRILILR.PRIL_Year_Of AS QUAL_Year_of_Qual,
RTRIM(PRFSFeesCostRecovery.PRFS_Nominal) AS Cost_Recovery_AC,
RTRIM(PRFSFeesTuition.PRFS_Nominal) AS Tuition_Fees_AC,
Cost_Centres.Cost_Centre,
/********* TUI24+FC ************ */
FC_Cost_Centres.FC_Cost_Centre,
RTRIM(PRFSFeesTrainingCredit.PRFS_Nominal) AS Training_Credit_AC,
RTRIM(PRFSFeesExam.PRFS_Nominal) AS Exam_Fees_AC,
RTRIM(PRFSFeesMaterials.PRFS_Nominal) AS Material_Fees_AC,
RTRIM(PRFSFeesRegn.PRFS_Nominal) AS Regn_Fee_AC,
dbo.PRILILR.PRIL_Funding_A10 AS FEFC_Fund_Q10,
dbo.GNCDgncodes.GNCD_Description AS Funding_Description,
dbo.PRPIProvisionInstance.PRPI_Max AS QUAL_Max_Size,
NULL AS National_Rate_1,
dbo.PRPIProvisionInstance.PRPI_Length_Years AS No_Of_Years,
dbo.PRPIProvisionInstance.PRPI_Instance AS Instance,
dbo.PRPHProvisionHeader.PRPH_Type,
dbo.PRPIProvisionInstance.PRPI_Code AS Qual_Instance_Code,
-- dbo.PRPIProvisionInstance.PRPI_MOA AS MOA_Code,
dbo.PRILILR.PRIL_Workplace_Learning AS WPL,
------------------- Columns swapped around ------------
-- dbo.ALL_ANNUAL_VALUES.SSA_TIER1_CODE AS Subject_sector_area,
CASE WHEN [dbo].[Core_LARS_LearningDelivery].SectorSubjectAreaTier1 > 0
THEN RIGHT('0' + CAST(CAST([dbo].[Core_LARS_LearningDelivery].SectorSubjectAreaTier1 AS INT) AS VARCHAR),2) END AS Subject_sector_area,
--£££££££££££££
dbo.PRILILR.PRIL_Title as Marketing_Title,
dbo.PRILILR.PRIL_Delivery_Postcode_A23,
------------------------------------------------
RTRIM(dbo.PRPHProvisionHeader.PRPH_Subject) as Sub_Section
------------------------------------------------
FROM dbo.PRILILR LEFT OUTER JOIN
dbo.PRPHProvisionHeader INNER JOIN
dbo.PRPIProvisionInstance ON
dbo.PRPHProvisionHeader.PRPH_Code = dbo.PRPIProvisionInstance.PRPI_Code LEFT OUTER JOIN
dbo.PRCOCoordinators ON dbo.PRPHProvisionHeader.PRPH_Code = dbo.PRCOCoordinators.PRCO_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = dbo.PRCOCoordinators.PRCO_Instance
LEFT OUTER JOIN
[dbo].[Core_LARS_LearningDelivery] ON dbo.PRPIProvisionInstance.PRPI_Aim COLLATE Latin1_General_CI_AS = [dbo].[Core_LARS_LearningDelivery].[LearnAimRef] LEFT OUTER JOIN
(SELECT [dbo].[Core_LARS_AnnualValue].*
FROM [dbo].[Core_LARS_AnnualValue] INNER JOIN
(SELECT [LearnAimRef], MAX([EffectiveFrom]) LatestDate
FROM [dbo].[Core_LARS_AnnualValue]
GROUP BY LearnAimRef) LatestAV ON LatestAV.LearnAimRef = [dbo].[Core_LARS_AnnualValue].[LearnAimRef] AND LatestAV.LatestDate = [dbo].[Core_LARS_AnnualValue].[EffectiveFrom]) AV ON dbo.PRPIProvisionInstance.PRPI_Aim COLLATE Latin1_General_CI_AS = AV.LearnAimRef LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesTuition ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesTuition.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesTuition.PRFS_Instance AND PRFSFeesTuition.PRFS_Fee_Type = 'TUICF' --'TUI'
/********* TUI24+FC ************ */
LEFT OUTER JOIN
dbo.PRFSFees AS FullCost_24plus ON dbo.PRPHProvisionHeader.PRPH_Code = FullCost_24plus.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = FullCost_24plus.PRFS_Instance AND (FullCost_24plus.PRFS_Fee_Type = 'TUI24+FC')
-----------------------
LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesUniform ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesUniform.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesUniform.PRFS_Instance AND PRFSFeesUniform.PRFS_Fee_Type = 'UNIFORM'
LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesKit ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesKit.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesKit.PRFS_Instance AND PRFSFeesKit.PRFS_Fee_Type = 'Kit'
--------------------
LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesCostRecovery ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesCostRecovery.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesCostRecovery.PRFS_Instance AND
PRFSFeesCostRecovery.PRFS_Fee_Type = 'COST REC'
LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesMaterials ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesMaterials.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesMaterials.PRFS_Instance AND PRFSFeesMaterials.PRFS_Fee_Type = 'MAT' LEFT OUTER JOIN
-----------------------------Full Cost Materials Fees---------------------------------------------------------------------------------------------------
dbo.PRFSFees AS FullCostMaterialsFees ON dbo.PRPHProvisionHeader.PRPH_Code = FullCostMaterialsFees.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = FullCostMaterialsFees.PRFS_Instance AND FullCostMaterialsFees.PRFS_Fee_Type = 'MATCF' LEFT OUTER JOIN
-----------------------------CRB Fees---------------------------------------------------------------------------------------------------
dbo.PRFSFees AS CRB_Fees ON dbo.PRPHProvisionHeader.PRPH_Code = CRB_Fees.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = CRB_Fees.PRFS_Instance AND CRB_Fees.PRFS_Fee_Type = 'UCF5' LEFT OUTER JOIN
--------------------------------------------------------------------------------------------------------------------------------------------------------
dbo.PRFSFees AS PRFSFeesExam ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesExam.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesExam.PRFS_Instance AND PRFSFeesExam.PRFS_Fee_Type = 'EXM' LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesTrainingCredit ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesTrainingCredit.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesTrainingCredit.PRFS_Instance AND
PRFSFeesTrainingCredit.PRFS_Fee_Type = 'TRAIN CRED' LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesOverseas ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesOverseas.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesOverseas.PRFS_Instance AND
PRFSFeesOverseas.PRFS_Fee_Type = 'NONEU' LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesRegn ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesRegn.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesRegn.PRFS_Instance AND PRFSFeesRegn.PRFS_Fee_Type = 'REG' LEFT OUTER JOIN
dbo.PRFSFees AS PRFSFeesUserFee5 ON dbo.PRPHProvisionHeader.PRPH_Code = PRFSFeesUserFee5.PRFS_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = PRFSFeesUserFee5.PRFS_Instance AND PRFSFeesUserFee5.PRFS_Fee_Type = 'UCF5' LEFT OUTER JOIN
dbo.PRTTTutors ON dbo.PRPHProvisionHeader.PRPH_Code = dbo.PRTTTutors.PRTT_Code AND
dbo.PRPIProvisionInstance.PRPI_Instance = dbo.PRTTTutors.PRTT_Instance LEFT OUTER JOIN
dbo.PERSstaff ON dbo.PRTTTutors.PRTT_Tutor = dbo.PERSstaff.PERS_Staff_Code LEFT OUTER JOIN
dbo.IM_LU_Sections_vw ON dbo.PRPHProvisionHeader.PRPH_ML2 = dbo.IM_LU_Sections_vw.Section_Code LEFT OUTER JOIN
dbo.IM_LU_Departments_vw ON dbo.PRPHProvisionHeader.PRPH_ML1 = dbo.IM_LU_Departments_vw.Department_Code LEFT OUTER JOIN
dbo.IM_LU_Departments_vw AS IM_LU_Departments_vw1 ON dbo.PERSstaff.PERS_Department_ML = IM_LU_Departments_vw1.Department_Code ON
dbo.PRILILR.PRIL_Code = dbo.PRPHProvisionHeader.PRPH_Code AND
dbo.PRILILR.PRIL_Instance = dbo.PRPIProvisionInstance.PRPI_Instance LEFT OUTER JOIN
dbo.GNCDgncodes ON dbo.GNCDgncodes.GNCD_General_Code = dbo.PRILILR.PRIL_Funding_A10 AND
dbo.GNCDgncodes.GNCD_Code_Type = 'CH' AND dbo.GNCDgncodes.GNCD_Level <= 98 LEFT OUTER JOIN
(SELECT PRFS_Code AS Code, PRFS_Instance AS Instance, RTRIM(PRFS_Finance_Dept) AS Cost_Centre
FROM dbo.PRFSFees
WHERE (PRFS_Fee_Type = 'TUICF')--'TUI'
GROUP BY PRFS_Code, PRFS_Instance, PRFS_Finance_Dept) AS Cost_Centres ON
dbo.PRPHProvisionHeader.PRPH_Code = Cost_Centres.Code AND dbo.PRPIProvisionInstance.PRPI_Instance = Cost_Centres.Instance
/********* TUI24+FC ************ */
LEFT OUTER JOIN
(SELECT PRFS_Code AS Code, PRFS_Instance AS Instance, RTRIM(PRFS_Finance_Dept) AS FC_Cost_Centre
FROM dbo.PRFSFees
WHERE (PRFS_Fee_Type = ('TUI24+FC'))--'TUI'
GROUP BY PRFS_Code, PRFS_Instance, PRFS_Finance_Dept) AS FC_Cost_Centres ON
dbo.PRPHProvisionHeader.PRPH_Code = FC_Cost_Centres.Code
AND dbo.PRPIProvisionInstance.PRPI_Instance = FC_Cost_Centres.Instance
-------------------
WHERE (dbo.PRPHProvisionHeader.PRPH_Type = 'Q')
Any help is appreciated.
Thanks,
Ar

You should look into dbo.IM_EN_Main_Qualifcation_with_title_vw. Your problem is that you are doing something like
c1 + c2
where c1 and c2 are columns, c1 is of type smallint, c2 is textual and when the view was created, c2 contained only numeric values, but recently a textual data was added, which contains '20PA'. You need to change the view to convert c1 to textual data, using CAST or CONVERT.
EDIT
As Aruna Raghuna pointed out, it turned out to be an issue in the College_Year column, which in at least a case, instead of the expected numeric value contained text as well. While I have shown the op the way to find the answer, frankly, it was Aruna, who searched for the issue. Thought process being used was as follows:
check column types and find out which are of smallint types, so that we will know where to look for the problem
check textual columns and find out which of those contained the text found in the error message
possible final step is to fix either the query or the functionality along with the data, so this kind of issue will not be recurring in the future

Related

Resolve SQL Server consuming long execution

The below query is of a view for which a top 10 * taking 1 minute 58 seconds sometime 2 minutes 30 seconds also, need help to tune the query all the joined tables have indexes already created.
The below query has CTE expressions and multiple joins and case statements. Need help on tuning the below query.
WITH CrmStatus AS
(SELECT DISTINCT
ESTAT,
StatusShortDesc,
sp.ProcessType
FROM refCRMStatus cs WITH (NOLOCK)
INNER JOIN refCRMStatusProfile sp ON sp.Processprofile = cs.ProcessType),
CTEOrgMaan1 AS
(SELECT Sorg.DistributionChannel AS DistributionChannel,
SO.Objectname AS SalesOffCode,
SOr.Objectname AS SalesOrgID,
SGrp.Objectname AS SalesGroup,
dvnb.DivisionName AS Brand,
Sorg.[H_CRMDOrgmanHSK],
Lnkorg.[H_CMRDLinkHSK],
[H_OpportunityHSK]
FROM [dbo].[S_CMRDOrgman] Sorg WITH (NOLOCK)
INNER JOIN [dbo].[L_CMRDLinkOrgman] Lnkorg WITH (NOLOCK) ON Lnkorg.[H_CRMDOrgmanHSK] = Sorg.[H_CRMDOrgmanHSK]
INNER JOIN vw_DivisionorBrand dvnb ON dvnb.DivisionCode = Sorg.DIVISION
INNER JOIN [dbo].[refSalesOfficeCRM] SO ON SO.[SalesOfficeID] = Sorg.SALESOFFICE
INNER JOIN [dbo].[refSalesOrgCRM] SOr ON SOr.[SalesOrgID] = Sorg.SALESORG
INNER JOIN [dbo].[refSalesGroupCRM] SGrp ON SGrp.[SalesGroupID] = Sorg.SalesGroup),
CTEAppoint AS
(SELECT HO.H_OpportunityHSK,
HO.ProcessType AS BusinessTransType,
refPt.ObjectType AS ObjectType,
refPt.processDesc AS ProcessDesc,
LeadGUID AS CRMOrderGUID,
SA.[APPLGUID],
SA.[APPTGUID],
SA.AppntID,
SA.ApptType AS AppointmentType,
SA.ApptText AS TextofAppointment,
SA.[CreatedBy],
SA.[ChangedBy],
SA.Startdate,
SA.FromTime,
SA.[AppntStartTimeZone] AS AppointmentStartTimeZone,
SA.[AppntStartTime] AS AppointmentStartTime,
SA.EndDate,
SA.ToTime,
SA.[AppntEndTimeZone] AS AppointmentEndTimeZone,
SA.[AppntEndTime] AS AppointmentEndTime,
SA.CreationDate,
SA.CreationTime,
SA.TimeStampCreation,
SA.ChangedOn,
SA.LastChangedAt,
SA.[TimeStampChangeTime] AS TimeStampOfChangeTime
FROM [dbo].[H_Opportunity] HO
INNER JOIN [dbo].[L_AppointmentorderADM] LA ON LA.[H_OpportunityHSK] = HO.[H_OpportunityHSK]
INNER JOIN [dbo].s_Appointment SA --with (index ([NonClusteredIndex-20200507-034807]))
ON LA.[L_AppointmentOrderADMHSK] = SA.[L_AppointmentOrderADMHSK]
INNER JOIN [dbo].[refProcessType] refPt ON refPt.[ProcessType] = HO.ProcessType)
SELECT a.*,
CTEOrgMaan.SalesOffCode,
CTEOrgMaan.SalesGroup,
CTEOrgMaan.SalesOrg AS SalesOrgID,
CTEOrgMaan.DistributionChannel,
CTEOrgMaan.Brand
FROM (SELECT DISTINCT
CApp.H_OpportunityHSK,
CApp.BusinessTransType,
CApp.ObjectType,
CApp.ProcessDesc,
CApp.CRMOrderGUID,
CApp.[APPLGUID],
CApp.[APPTGUID],
CApp.AppntID,
CApp.AppointmentType,
CApp.TextofAppointment,
CApp.[CreatedBy],
CApp.[ChangedBy],
CApp.Startdate,
CApp.FromTime,
CApp.AppointmentStartTimeZone,
CApp.AppointmentStartTime,
CApp.EndDate,
CApp.ToTime,
CApp.AppointmentEndTimeZone,
CApp.AppointmentEndTime,
CApp.CreationDate,
CApp.CreationTime,
CApp.TimeStampCreation,
CApp.ChangedOn,
CApp.LastChangedAt,
CApp.TimeStampOfChangeTime,
PARTNERFCT AS PartnerFunction,
rfct.DESCRIPTION AS PartnerDesc,
PartnerNo,
Partnerguid,
MainPartner AS MainPartnerFlag,
St.[Stat] AS Status,
stu.[StatusShortDesc],
CASE WHEN CC.CompanyName IS NOT NULL THEN CC.CompanyName ELSE CI.FullName END AS CustomerName,
CONVERT(varchar(MAX),
CASE
WHEN CC.H_EngageCustomerHSK IS NOT NULL THEN CC.H_EngageCustomerHSK
ELSE CASE
WHEN CI.H_EngageCustomerHSK IS NULL THEN CONVERT(uniqueidentifier, (HASHBYTES('Md5', 'NA')))
ELSE CI.H_EngageCustomerHSK
END
END) AS CustomerHSK,
CASE WHEN CC.CustomerType IS NOT NULL THEN CC.CustomerType ELSE CI.CustomerType END AS CustomerType
FROM [dbo].[H_CMRDPartner] Hp
LEFT JOIN [dbo].[S_CMRPartner] Sp ON Hp.[H_CMRDPartnerHSK] = Sp.[H_CMRDPartnerHSK]
INNER JOIN [dbo].[L_CRMDPartner] LCP ON LCP.[H_CMRDPartnerHSK] = Hp.[H_CMRDPartnerHSK]
LEFT JOIN [dbo].[L_CRMDCustomerPartner] CCP ON CCP.[H_CMRDPartnerHSK] = Hp.[H_CMRDPartnerHSK]
LEFT JOIN S_CustomerCompany CC ON CC.H_EngageCustomerHSK = CCP.[H_EngageCustomerHSK]
LEFT OUTER JOIN S_CustomerIndividual CI ON CI.H_EngageCustomerHSK = CCP.[H_EngageCustomerHSK]
LEFT JOIN CTEAppoint CApp ON CApp.H_OpportunityHSK = LCP.H_OpportunityHSK
INNER JOIN [dbo].[S_CRMOrderADMStatus] St ON St.[H_OpportunityHSK] = CApp.H_OpportunityHSK
INNER JOIN CrmStatus stu ON stu.ESTAT = St.Stat
AND stu.processType = CApp.BusinessTransType
LEFT JOIN refCRMCPartnerFCT rfct ON rfct.[PARTNER_FCT] = Sp.PartnerFCT
WHERE Sp.PartnerFCT = '00000009') a
INNER JOIN vw_getCRMDOrgman_new CTEOrgMaan ON CTEOrgMaan.H_OpportunityHSK = a.H_OpportunityHSK;
GO

Multi-part identifier could not be bound?

drop table #test1
/*** Master Validation Query!!!!!DO NOT CHANGE GROUPINGS!!!!**/
/**07/25/2007
1. Updated Discount code to link back to worktable
2. Updated U&C Calculation
3. Updated Non_covered calculation
*********************************************/
select
min(clm_net) as ProNet,
min(v1.val_opt) as opt,
min(clm_prod) as prod,
min(c.clm_drgc) as drgcode,
min(c.clm_4) as clm_4,
min(c.clm_cc2) as clm_cc2,
min(c.clm_cc3) as clm_cc3,
min(c.clm_3) as clm_3,
min(c.clm_38a) as clm_38a,
min(c.clm_38b) as clm_38b,
min(c.clm_12a) as clm_12a,
min(c.clm_12b) as clm_12b,
min(c.clm_60a) as clm_60a,
min(m.mem_altid) as AltId,
min(c.clm_5) as clm_5,
min(c.clm_1a1) as clm_1a1 ,
min(c.clm_1a2) as clm_1a2,
min(c.clm_deg) as clm_deg,
min(pro_spec1) as specialty,
min(v3.val_desc) as ProDesc1,
min(pro_xtyp) as protype,
min(c.clm_1a) as clm_1a,
min(c.clm_batch) as clm_batch,
min(c.clm_id1) as clm_id1,
min(s.clms_line) as clms_line,
min(s.clms_from) as clms_from,
min(s.clms_thru) as clms_thru,
impact.dbo.u_poscalc3(min(clm_form),min(clm_4),min(clms_rev),min(clm_spc),min(clms_pos),min(clms_ben),min(clm_67)) as clm_POS,
min(s.clms_rev) as clms_rev,
min(v6.val_desc) as procdesc2,
min(s.clms_proc) as clms_proc,
min(v4.val_desc) as procdesc,
min(s.clms_mod1) as clms_mod1,
min(v5.val_desc) as moddesc,
min(c.clm_67) as Diagnosis,
min(v1.val_desc) as Dcode,
min(v1.val_opt) as class,
min(v2.val_desc) as Dclass,
min(c.clm_68) as clm_68,
min(c.clm_69) as clm_69,
min(s.clms_chg) as clms_chg,
min(s.clms_sku) as clms_sku,
min(s.clms_allow) as clms_allow,
min(s.clms_copa) as clms_copa,
min(s.clms_dedu) as clms_dedu,
min(s.clms_coin) as clms_coin,
min(s.clms_non) as clms_non,
min(s.clms_cobp) as clms_cobp,
min(s.clms_wh) as clms_wh,
min(s.clms_payp) as clms_payp,
min(s.clms_paye) as clms_paye,
min(c.clm_inet) as clm_inet,
min(s.clms_ben) as clms_ben,
min(c.clm_form) as clm_form,
Min(c.clm_stades) as clm_stades,
min(c.clm_edid) as clm_edid,
Min(c.clm_chkno) as clm_chkno,
min(c.clm_dout) as clm_dout,
min(c.clm_chgdt) as clm_chgdt,
min(c.clm_ips) as clm_ips,
min(c.clm_den) as Den,
min(clm_pclm) as TXENnum,
min(d.clmd_cm01) as prindiag,
min(icd10.DIAG_CODE) as diagcode
into #test1
from impact.dbo.tbl_clm c
left join impact.dbo.tbl_mem m on m.mem_id1 = c.clm_12
left join impactwork.dbo.icd_diag_codes icd9 on icd9.diag_code = left(c.clm_67, 3) and icd9.code_type = 'ICD9_DIAG'
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
left join impact.dbo.tbl_meme e on e.meme_id1 = c.clm_12
left join impact.dbo.tbl_clms s on s.clms_id = c.clm_id1
left join impact.dbo.tbl_valid diag on diag.val_code = clm_67 and diag.val_type = '503'
left join tbl_valid v1 on v1.val_type = '57a'and v1.val_code = c.clm_67 --primary diagnosis
left join tbl_valid v2 on v2.val_type = '57b' and v2.val_code = v1.val_opt -- The val_opt of the code relates to the class
left join impact.dbo.tbl_pro p on c.clm_1 = p.pro_id1
left join tbl_valid v3 on v3.val_type = '302'and v3.val_code = pro_spec1
left join tbl_valid v4 on v4.val_type = '501' and v4.val_code = clms_proc
left join tbl_valid v5 on v5.val_type = '502' and v5.val_code = clms_mod1
left join tbl_valid v6 on v6.val_type = '506' and v6.val_code = clms_rev
where c.clm_stades = 'paid'
and c.clm_stades != 'dupl'
and clm_form != 'B'
and clms_Actn != 'Change'
and c.clm_prod !='den'
and c.clm_dout between '01/01/2015' and '05/31/2015'
and c.clm_prod <> 'flx'
and clm_cc2 in ('52037')
group by c.clm_id1,s.clms_line,c.clm_cc2
order by c.clm_Id1,s.clms_line,c.clm_cc2
select *
from #test1
I am getting an error:
on line 85 stating, 'The multi-part identifier "d.clmd_cm01" could
not be bound.
Why am I getting such an error? I looked to make sure that all of my aliases are used in the join, but that doesn't seem to be the problem.
You need to have the join:
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
before
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
As the above join uses a column from impact.dbo.tbl_clmd d as a join predicate.
This should work:
drop table #test1
/*** Master Validation Query!!!!!DO NOT CHANGE GROUPINGS!!!!**/
/**07/25/2007
1. Updated Discount code to link back to worktable
2. Updated U&C Calculation
3. Updated Non_covered calculation
*********************************************/
select
min(clm_net) as ProNet,
min(v1.val_opt) as opt,
min(clm_prod) as prod,
min(c.clm_drgc) as drgcode,
min(c.clm_4) as clm_4,
min(c.clm_cc2) as clm_cc2,
min(c.clm_cc3) as clm_cc3,
min(c.clm_3) as clm_3,
min(c.clm_38a) as clm_38a,
min(c.clm_38b) as clm_38b,
min(c.clm_12a) as clm_12a,
min(c.clm_12b) as clm_12b,
min(c.clm_60a) as clm_60a,
min(m.mem_altid) as AltId,
min(c.clm_5) as clm_5,
min(c.clm_1a1) as clm_1a1 ,
min(c.clm_1a2) as clm_1a2,
min(c.clm_deg) as clm_deg,
min(pro_spec1) as specialty,
min(v3.val_desc) as ProDesc1,
min(pro_xtyp) as protype,
min(c.clm_1a) as clm_1a,
min(c.clm_batch) as clm_batch,
min(c.clm_id1) as clm_id1,
min(s.clms_line) as clms_line,
min(s.clms_from) as clms_from,
min(s.clms_thru) as clms_thru,
impact.dbo.u_poscalc3(min(clm_form),min(clm_4),min(clms_rev),min(clm_spc),min(clms_pos),min(clms_ben),min(clm_67)) as clm_POS,
min(s.clms_rev) as clms_rev,
min(v6.val_desc) as procdesc2,
min(s.clms_proc) as clms_proc,
min(v4.val_desc) as procdesc,
min(s.clms_mod1) as clms_mod1,
min(v5.val_desc) as moddesc,
min(c.clm_67) as Diagnosis,
min(v1.val_desc) as Dcode,
min(v1.val_opt) as class,
min(v2.val_desc) as Dclass,
min(c.clm_68) as clm_68,
min(c.clm_69) as clm_69,
min(s.clms_chg) as clms_chg,
min(s.clms_sku) as clms_sku,
min(s.clms_allow) as clms_allow,
min(s.clms_copa) as clms_copa,
min(s.clms_dedu) as clms_dedu,
min(s.clms_coin) as clms_coin,
min(s.clms_non) as clms_non,
min(s.clms_cobp) as clms_cobp,
min(s.clms_wh) as clms_wh,
min(s.clms_payp) as clms_payp,
min(s.clms_paye) as clms_paye,
min(c.clm_inet) as clm_inet,
min(s.clms_ben) as clms_ben,
min(c.clm_form) as clm_form,
Min(c.clm_stades) as clm_stades,
min(c.clm_edid) as clm_edid,
Min(c.clm_chkno) as clm_chkno,
min(c.clm_dout) as clm_dout,
min(c.clm_chgdt) as clm_chgdt,
min(c.clm_ips) as clm_ips,
min(c.clm_den) as Den,
min(clm_pclm) as TXENnum,
min(d.clmd_cm01) as prindiag,
min(icd10.DIAG_CODE) as diagcode
into #test1
from impact.dbo.tbl_clm c
left join impact.dbo.tbl_mem m on m.mem_id1 = c.clm_12
left join impactwork.dbo.icd_diag_codes icd9 on icd9.diag_code = left(c.clm_67, 3) and icd9.code_type = 'ICD9_DIAG'
left join impact.dbo.tbl_clmd d on clmd_id1 = c.clm_id1
left join impactwork.dbo.icd_diag_codes icd10 on icd10.diag_code = left(d.clmd_cm01, 3) and icd10.code_type = 'ICD10_DIAG'
left join impact.dbo.tbl_meme e on e.meme_id1 = c.clm_12
left join impact.dbo.tbl_clms s on s.clms_id = c.clm_id1
left join impact.dbo.tbl_valid diag on diag.val_code = clm_67 and diag.val_type = '503'
left join tbl_valid v1 on v1.val_type = '57a'and v1.val_code = c.clm_67 --primary diagnosis
left join tbl_valid v2 on v2.val_type = '57b' and v2.val_code = v1.val_opt -- The val_opt of the code relates to the class
left join impact.dbo.tbl_pro p on c.clm_1 = p.pro_id1
left join tbl_valid v3 on v3.val_type = '302'and v3.val_code = pro_spec1
left join tbl_valid v4 on v4.val_type = '501' and v4.val_code = clms_proc
left join tbl_valid v5 on v5.val_type = '502' and v5.val_code = clms_mod1
left join tbl_valid v6 on v6.val_type = '506' and v6.val_code = clms_rev
where c.clm_stades = 'paid'
and c.clm_stades != 'dupl'
and clm_form != 'B'
and clms_Actn != 'Change'
and c.clm_prod !='den'
and c.clm_dout between '01/01/2015' and '05/31/2015'
and c.clm_prod <> 'flx'
and clm_cc2 in ('52037')
group by c.clm_id1,s.clms_line,c.clm_cc2
order by c.clm_Id1,s.clms_line,c.clm_cc2
select *
from #test1
Table impact.dbo.tbl_clmd is aliased as d (longer aliases FTW, helps readability). If you're seeing the error
'The multi-part identifier "d.clmd_cm01" could not be bound.
Then I'd be almost certain that table impact.dbo.tbl_clmd doesn't contain a column clmd_cm01.
EDIT - Kamran Farzami's spotted what I missed, that the table aliased in d is only joined in after it's been used as a join criteria. In any RDMBS I've used they have to be declared in order - you can't depend on what hasn't already been referenced in the query.

SQLTimeout when executing stored procedure in SQL Server 2012

I'm getting an error:
System.Data.SqlClient.SqlException: Timeout expired
with a stored procedure when the result set is above a certain record count. Unfortunately this error is only occurring in a production environment which I have very limited access to.
This is a legacy application and I didn't build this stored procedure, so I have to be careful about changes altering it's expected (but undocumented) behavior. I have a .NET background, but limited SQL Server experience.
The highest number of records that could be returned is 5000 (this is how many records are currently in the db). I don't know the exact threshold where it starts to fail, but it's somewhere between 2500 and the maximum 5000 records.
The stored procedure in question consists only of two SELECT statements unioned together. Using SQL Server Profiler on my dev machine didn't reveal anything useful. Is there anything obviously wrong with this stored procedure that would cause it to exceed the 30 second timeout?
SELECT
tblRed.PhaseID, tblRed.EventID, tblRed.RMUserID, tblRed.BackupRMUserID,
tblRed.AuthorUserID, tblRed.StageID, tblRed.Status,
tblRed.PublicationDateActual, tblGreen.SystemName, tblGreen.StakeholderDisplayName,
tblGreen.StakeholderQueue, tblRed.EventTypeID,
tblRed.StageReceivedDate, tblRed.StageDueDate, tblRed.SubmitDate, tblBlue.Name,
tblBlue.Email, tblBlue.PhoneNumber, tblBrown.EventName,
MIN(tblCharm.CommunicationMaterialTypeName) AS CommunicationMaterialTypeName,
MIN(tblUp.AttachmentID) AS AttachmentID,
tblOld.SmartFormID, tblOld.isGenerated,
MIN(tblStrange.SupportDocumentTypeID) AS SupportDocumentTypeName
FROM
tblDude
INNER JOIN
tblDown ON tblDude.TeamID = tblDown.TeamID
INNER JOIN
tblGrey ON tblGrey.DepartmentID = tblDown.DepartmentID
LEFT OUTER JOIN
tblOrange ON tblOrange.DepartmentID = tblGrey.DepartmentID
LEFT OUTER JOIN
tblPurple ON tblPurple.TeamID = tblDown.TeamID
LEFT OUTER JOIN
tblPaper ON tblGrey.DivisionID = tblPaper.DivisionID
LEFT OUTER JOIN
tblNavy ON tblPaper.DivisionID = tblNavy.DivisionID
INNER JOIN
tblRed ON tblRed.PhaseID = tblDude.PhaseID
INNER JOIN
tblGreen ON tblRed.StageID = tblGreen.StageID
INNER JOIN
tblBlue ON tblBlue.UserID = tblRed.AuthorUserID
INNER JOIN
tblBrown ON tblBrown.EventID = tblRed.EventID
LEFT OUTER JOIN
tblUp ON tblUp.PhaseID = tblRed.PhaseID
LEFT OUTER JOIN
tblCharm ON tblUp.CommunicationMaterialTypeID = tblCharm.CommunicationMaterialID
AND tblUp.isLatest = 'True'
LEFT OUTER JOIN
tblOld ON tblOld.PhaseID = tblRed.PhaseID
LEFT OUTER JOIN
tblStrange ON tblStrange.PhaseID = tblRed.PhaseID
WHERE
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblDude.SMEUserID = #UserID))
OR
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblGrey.DeptSignatoryUserID = #UserID))
OR
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblPurple.DelegateUserID = #UserID))
OR
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblOrange.DelegateUserID = #UserID))
OR
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblNavy.UserID = #UserID))
OR
((tblRed.AuthorUserID <> #UserID)
AND (tblRed.Status = 'Active')
AND (tblGreen.StakeholderQueue = 'History')
AND (tblPaper.DivisionSignatoryUserID = #UserID))
GROUP BY
tblRed.PhaseID, tblRed.EventID, tblRed.RMUserID, tblRed.BackupRMUserID,
tblRed.AuthorUserID, tblRed.StageID, tblRed.Status, tblRed.PublicationDateActual,
tblGreen.SystemName, tblGreen.StakeholderDisplayName, tblGreen.StakeholderQueue,
tblRed.EventTypeID, tblRed.StageReceivedDate, tblRed.StageDueDate, tblRed.SubmitDate,
tblBlue.Name, tblBlue.Email, tblBlue.PhoneNumber, tblBrown.EventName,
tblOld.SmartFormID, tblOld.isGenerated
UNION
SELECT DISTINCT
tblRed.PhaseID, tblRed.EventID, tblRed.RMUserID, tblRed.BackupRMUserID,
tblRed.AuthorUserID, tblRed.StageID, tblRed.Status,
tblRed.PublicationDateActual, tblGreen.SystemName, tblGreen.StakeholderDisplayName,
tblGreen.StakeholderQueue, tblRed.EventTypeID,
tblRed.StageReceivedDate, tblRed.StageDueDate, tblRed.SubmitDate, tblBlue.Name,
tblBlue.Email, tblBlue.PhoneNumber, tblBrown.EventName,
MIN(tblCharm.CommunicationMaterialTypeName) AS CommunicationMaterialTypeName,
MIN(tblUp.AttachmentID) AS AttachmentID,
tblOld.SmartFormID, tblOld.isGenerated,
MIN(tblStrange.SupportDocumentTypeID) AS SupportDocumentTypeName
FROM
tblRed
INNER JOIN
tblGreen ON tblRed.StageID = tblGreen.StageID
LEFT OUTER JOIN
tblBlue ON tblRed.RMUserID = tblBlue.UserID
INNER JOIN
tblBrown ON tblRed.EventID = tblBrown.EventID
LEFT OUTER JOIN
tblUp ON tblUp.PhaseID = tblRed.PhaseID
LEFT OUTER JOIN
tblCharm ON tblUp.CommunicationMaterialTypeID = tblCharm.CommunicationMaterialID
AND tblUp.isLatest = 'True'
LEFT OUTER JOIN
tblOld ON tblOld.PhaseID = tblRed.PhaseID
LEFT OUTER JOIN
tblStrange ON tblStrange.PhaseID = tblRed.PhaseID
WHERE
tblRed.Status = 'Active'
AND tblGreen.AuthorQueue = 'History'
AND tblRed.AuthorUserID = #UserID
GROUP BY
tblRed.PhaseID, tblRed.EventID, tblRed.RMUserID, tblRed.BackupRMUserID,
tblRed.AuthorUserID, tblRed.StageID, tblRed.Status,
tblRed.PublicationDateActual, tblGreen.SystemName, tblGreen.StakeholderDisplayName,
tblGreen.StakeholderQueue, tblRed.EventTypeID, tblRed.StageReceivedDate,
tblRed.StageDueDate, tblRed.SubmitDate, tblBlue.Name, tblBlue.Email,
tblBlue.PhoneNumber, tblBrown.EventName, tblOld.SmartFormID, tblOld.isGenerated

what is this code doing can not understand it

I am trying to figure out what a query is doing and I just do not understand why it would join its self to its self on multiple occassions highlighted bit is the piece i am talking about?
its the part that starts with the [SupplyStatusUpdated] = COALESCE( gas supply and gas supply history
USE [CRM];
SELECT gs.GasSupplyID,
[Account ID] = acc.AccountID,
[GMSReference] = cast(gms.SiteRefNum as varchar),
[AccountNumber] = cast(gms.AccountNum as varchar),
[Organisation Name] = prf.[Name] ,
con.DeclaredDate,
[Contract Date] = CAST(con.ContractDate AS DATE),
[Contract Version] = cv.Name,
[Contract Status] = cs.Name,
loa.ContractEndDate [LOA CED],
gs.CurrentSupplierEndDate [PrevSupplierEndDate],
loa.ContractEndDate,
con.StartDate,
[Supply Status] = gss.Name,
[SupplyStatusUpdated] = COALESCE(
(
SELECT TOP 1 MAX(gsh2.CreatedDate)
FROM GasSupply gs2
INNER JOIN GasSupplyHistory gsh2
ON gsh2.GasSupplyFK = gs2.GasSupplyID
WHERE gsh2.EventFK = 2
AND gsh2.Notes LIKE '%Gas Supply Status (%'
AND gsh2.GasSupplyFK = gs.GasSupplyID
GROUP BY gsh2.GasSupplyFK
),
(
SELECT TOP 1 MAX(gsh3.CreatedDate)
FROM GasSupplyHistory gsh3
INNER JOIN (
SELECT gsh4.GasSupplyFK, MAX(gsh4.EventFK) AS [MaxEvent]
FROM GasSupplyHistory gsh4
WHERE gsh4.GasSupplyFK = gs.GasSupplyID
GROUP BY gsh4.GasSupplyFK
HAVING MAX(gsh4.EventFK) = 1
) dt
ON dt.GasSupplyFK = gsh3.GasSupplyFK
)
),
[EAC] = gs.EstimatedAnnualConsumption,
[PreviousSupplier] = r.name,
[Branch] = b.name,
[LeadSource] = ls.name,
gs.UnitPrice,
gs.StandingCharge,
gs.WholesalePrice,
COALESCE(deal.weeknumber,DATEPART(ISOWK, con.[ContractDate])) AS [Week]
FROM acc.Account acc
INNER JOIN [Profile] prf
ON acc.ProfileFK = prf.ProfileID
INNER JOIN [Contract] con
ON acc.AccountID = con.AccountFK
INNER JOIN [loacontract] lo
ON lo.ContractFK = con.ContractID
LEFT join [LeadSource] ls
ON ls.LeadSourceID = con.LeadSourceFK
INNER JOIN [ContractStatus] cs
ON cs.ContractStatusID = con.ContractStatusFK
INNER JOIN [ContractVersion] cv
ON cv.ContractVersionID = con.ContractVersionFK
INNER JOIN GasSupply gs
ON gs.ContractFK = con.ContractID
INNER JOIN GasSupplyStatus gss
ON gss.GasSupplyStatusID = gs.GasSupplyStatusFK
LEFT JOIN Deal deal
ON deal.ContractFK = con.ContractID
OUTER APPLY GetGMSReferenceNumbers(con.ContractID) gms
LEFT JOIN Branch b
ON b.BranchID = deal.BranchFK
LEFT JOIN DealBroker bro
ON bro.DealFK = deal.DealID
AND bro.BrokerTypeFK = 36
LEFT JOIN Person p
ON p.PersonID = bro.EmployeeFK
LEFT JOIN Reseller r
ON r.ResellerID = gs.ResellerFK
LEFT JOIN (
SELECT l.contractfk,
MIN(l.contractenddate)[ContractEndDate]
FROM CRM.[contract].LOAContract l
GROUP BY l.ContractFK
) loa
ON loa.ContractFK = con.ContractID
WHERE acc.AccountID not in (
select AccountFK
from AccountOption
where OptionFK=9
)
AND cast(gms.SiteRefNum as varchar) IS NULL
COALESCE(Something, SomethingElse) says if the first argument is NULL, return the second argument (note that you can have more than 2 args and it'll just keep going down the list).
As such it's running the first sub-query, and if the result is NULL, returning the result of the second query. Why exactly is your business logic, which we can't answer :-)
(MSDN link on Coalesce)
COALESCE returns the first non-null value it finds, so if the GasSupply query returns a result it will use that: if that returns null it will see if the GasSupplyHistory query returns a result, and if so use that. If both queries return null then SupplyStatusUpdated will be null.
It joins to itself to get historical records from the same source as where it gets the current record.
Representation of historical data is is one common reason for using a BigData/NoSQL database instead of a SQL/Relational database.

SQL with left outer join and 3 tables

I would like to add an ADD at the end of my code. Please have a look on my code and thanks for your support:
SELECT Area.org,
Supervisors.NomSup,
Supervisors.PrenomSup,
Employees.NomEmp,
Employees.PrenomEmp,
Employees.NoIdAlcanEmp,
Competencies.CodeCompetencies,
Competencies.CompetencyName,
LinkResultComp.AssNote,
LinkResultComp.AssDate
FROM ((((((
Area INNER JOIN Supervisors ON Area.IdArea = Supervisors.IdArea
)
INNER JOIN Employees ON Supervisors.IdSupervisor = Employees.IdSupervisor
)
INNER JOIN LinkProfilesEmployees ON Employees.IdEmp = LinkProfilesEmployees.IdEmp
)
INNER JOIN Profiles ON Profiles.IdProfiles = LinkProfilesEmployees.IdProfiles
)
INNER JOIN LinkProfComp ON Profiles.IdProfiles = LinkProfComp.IdProfiles
)
INNER JOIN Competencies ON Competencies.IdCompetencies = LinkProfComp.IdCompetencies
)
LEFT OUTER JOIN LinkResultComp ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies AND ON Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
WHERE Area.org LIKE "*20*" AND Competencies.CodeCompetencies LIKE "khse2010-05"
ORDER BY Supervisors.NomSup, Employees.NomEmp;
Just remove the extra ON that you added
So change this
LEFT OUTER JOIN LinkResultComp
ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies
AND ON Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
------^^ This one
to this
LEFT OUTER JOIN LinkResultComp
ON (Competencies.IdCompetencies = LinkResultComp.IdCompetencies
AND Competencies.IdCompetencies = LinkResultComp.IdCompetencies)
Of course I assume you meant different fields for the second condition