Resolve SQL Server consuming long execution - sql

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

Related

SQL Selects combine - Second select to be in Where clause

I have 2 selects. The first one:
select purs.t_orno as purchased
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5
Is giving me these results:
PUR007833
PUR008544
PUR008698
PUR008963
PUR009048
PUR009304
PUR009611
PUR009912
PUR009913
PUR010006
PUR010110
PUR010400
PUR010465
PUR010539
PUR010664
So basically these are results I must use in the second select in where clause. A field from table in second select must be equal to one of them. To understand me better it should look like this:
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
where mid.t_orno ='PUR010400' or mid.t_orno='PUR009912'or mid.t_orno='PUR009913'or mid.t_orno='PUR010465'or mid.t_orno='PUR008544'or mid.t_orno='PUR008963'or mid.t_orno='PUR009048'or mid.t_orno='PUR010110'or mid.t_orno='PUR007833'or mid.t_orno='PUR009304'or mid.t_orno='PUR009611'or mid.t_orno='PUR010664'or mid.t_orno='PUR010006'or mid.t_orno='PUR010539'or mid.t_orno='PUR008698'or mid.t_orno='PUR010667'
All these ORs are results from the first select. How I can combine them (the first select to go in second select where clause) so I can get results at once?
You can use the IN clause for your second query
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
where mid.t_orno IN (
select purs.t_orno
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5
)
Something like this
;with first_query_cte(purchased) as (
select purs.t_orno
from ttisfc001201 sls
inner join twhinr110201 sfc on sfc.t_orno = sls.t_pdno
inner join twhltc100201 purs on purs.t_clot=sfc.t_clot
left join twhltc220201 items on items.t_clot = sfc.t_clot
left join twhltc210201 cert_num on cert_num.t_item = items.t_item
left join twhltc200201 cert on cert.t_ltft = cert_num.t_ltft
where sls.t_cprj = 'SLS004336' and purs.t_orno like N'PUR%'
and sfc.t_koor = 1 and sfc.t_kost = 5)
select distinct fac.t_isup
from ttfacp200201 fac
inner join ttfacp250201 mid on mid.t_ityp = fac.t_ttyp and mid.t_idoc=fac.t_ninv
inner join first_query_cte fqc on mid.t_orno=fqc.purchased;

incorrect syntax near the keyword where for using subquery

SELECT DISTINCT dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from AS reprt,
#to AS reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id
WHERE dbo.setup_color.color_id=
(SELECT color_no
FROM dbo.setup_color) WHERE master_order.shipment_date>=#from
AND master_order.shipment_date<=#to
This is your syntax after WHERE clause
where dbo.setup_color.color_id=
(select color_no from dbo.setup_color)
where master_order.shipment_date>=
#from and master_order.shipment_date<=#to
there are 2 Where clauses used on main Query.
use in instead of equals for a subquery.
SELECT DISTINCT
dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from as reprt,
#to as reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id where dbo.setup_color.color_id in
(select color_no from dbo.setup_color) where master_order.shipment_date >= #from and master_order.shipment_date<= #to
The problem is that you have 2 WHERE clauses in the main query. as master_order is a table used in main query, just replace 2nd WHERE withAND as below.
SELECT DISTINCT dbo.master_order.order_no,
dbo.master_order.program_no,
dbo.Setup_size.size_name,
dbo.Setup_color.color_name,
dbo.Setup_color.color_no,
dbo.transaction_production.total_weight,
dbo.Setup_yarn.yarn_count,
dbo.Setup_article_order.article_name,
dbo.master_order.shipment_date,
#from AS reprt,
#to AS reprt1,
dbo.transaction_order.quantity,
dbo.transaction_order.gsm
FROM dbo.master_order
INNER JOIN dbo.transaction_order ON dbo.master_order.order_id = dbo.transaction_order.order_id
INNER JOIN dbo.transaction_production ON dbo.transaction_order.trans_id = dbo.transaction_production.trans_id
INNER JOIN dbo.Setup_size ON dbo.transaction_order.size_id = dbo.Setup_size.size_id
INNER JOIN dbo.Setup_yarn ON dbo.transaction_order.yarn_id = dbo.Setup_yarn.yarn_id
INNER JOIN dbo.Setup_article_order ON dbo.transaction_order.article_id = dbo.Setup_article_order.article_id
INNER JOIN dbo.Setup_color ON dbo.transaction_order.color_id = dbo.Setup_color.color_id
AND dbo.Setup_yarn.color_id = dbo.Setup_color.color_id
WHERE dbo.setup_color.color_id=
(SELECT color_no
FROM dbo.setup_color)
AND master_order.shipment_date>=#from
AND master_order.shipment_date<=#to
Also if the table dbo.setup_color has more than 1 value, either use IN instead of = or add a WHERE clause to the inner query to return just one value, otherwise it will throw error.

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

SQL Stored Procedure With One To Many Relationship Return Only Most Recent Record

I've been having a terrible time with this. I created a stored procedure to return a corresponding record, but one of the tables has multiple print jobs so it returns multiple records. I only want the most recent requested print job to return and I can't get it to work correctly.
Please help!
SELECT PrintJobs.WORDERKey,
PrintJobs.JobNumber,
WORDER.U_DateRequired AS DateRequired,
ProductMaster.PartFileItemID,
WORDER.ManufacturingDepartment AS MfgDept,
PrintJobs.Copies AS LabelCopies,
PrintJobs.ExpiryDate AS JobExpiryDate,
PrintJobs.Batch,
PrintJobs.JulianDate AS JobJulianDate,
ProductMaster.Description,
ProductMaster.PackFormat,
ProductMaster.IngDec,
ProductMaster.BarCodeNumber,
ProductMaster.CustomerProductCode,
ProductMaster.CriticalInstruction,
ProductMaster.StorageInstruction,
ProductMaster.MixedCaseTitle,
ProductMaster.MixedCode1,
ProductMaster.MixedCode2,
ProductMaster.MixedCode3,
ProductMaster.MixedCode4,
ProductMaster.MixedDescription1,
ProductMaster.MixedDescription2,
ProductMaster.MixedDescription3,
ProductMaster.MixedDescription4,
ProductMaster.MixedIngDec1,
ProductMaster.MixedIngDec2,
ProductMaster.MixedIngDec3,
ProductMaster.MixedIngDec4,
ProductMaster.CookingInstruction,
ProductMaster.LogoFilename,
ProductMaster.ProductExpiryRule,
ExpiryRulesMaster.GS1_AppID,
ProductMaster.LabelTemplateID,
CASE WHEN ProductMaster.PartFileItemID IS NULL THEN 'N' ELSE 'Y' END AS LabelDefExists,
LabelTemplateMaster.FileName,
CASE WHEN [DateFormat] = 'Default' THEN ExpiryRulesMaster.DateFormatString ELSE [DateFormat] END AS DateFormatString,
ExpiryRulesMaster.DateRounding,
ExpiryRulesMaster.ExcludeXmasNewYear,
PART.ExternalShelfLifeTotalDays,
CustomOptions.Tagline,
CustomOptions.ShortName AS CustShortName,
ExpiryRulesMaster.LabelText AS ExpiryRuleLabelText,
ProductMaster.inner_hDescription,
ProductMaster.inner_vDescription,
ProductMaster.inner_CustCode,
ProductMaster.inner_Storage,
ProductMaster.inner_WarningMsg,
ProductMaster.inner_Dateformat,
ProductMaster.inner_SpecialCode,
ProductMaster.LabelType,
ProductMaster.inner_MicroSuiteCode,
ProductMaster.inner_PackWeight,
ProductMaster.inner_JDateFormat,
ProductMaster.CustomOptionID,
ProductMaster.inner_PrintLogo,
PART.NominalWeight,
ProductMaster.IngDec_html,
ProductMaster.IngDec_Active,
PrintJobs.PrintJobsID,
MaxJobs.MaxJob,
PrintJobs.DateEntered
FROM ProductMaster RIGHT OUTER JOIN
(
SELECT Partfileitemid,
--JobNumber,
MAX(dateentered) MaxJob
FROM PrintJobs
GROUP BY PartFileItemID
)
MaxJobs ON ProductMaster.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
PrintJobs ON PrintJobs.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
LabelTemplateMaster ON ProductMaster.LabelTemplateID = LabelTemplateMaster.LabelTemplateID LEFT OUTER JOIN
CustomOptions ON ProductMaster.CustomOptionID = CustomOptions.CustomOptionID LEFT OUTER JOIN
ExpiryRulesMaster ON ProductMaster.ProductExpiryRule = ExpiryRulesMaster.ExpiryRule LEFT OUTER JOIN
[F8Extract].[dbo].[WORDER] ON PrintJobs.WORDERKey = WORDER.WORDERKey LEFT OUTER JOIN
[F8Extract].[dbo].[PART] ON ProductMaster.PartFileItemID = Part.PartFileItemID
WHERE PrintJobs.WORDERKey = #WORDERKey
END
Thanks,
Stacy
One way would be to look at TOP and ORDER BY, i.e.
SELECT TOP 1
PrintJobs.WORDERKey,
PrintJobs.JobNumber,
WORDER.U_DateRequired AS DateRequired,
ProductMaster.PartFileItemID,
WORDER.ManufacturingDepartment AS MfgDept,
PrintJobs.Copies AS LabelCopies,
PrintJobs.ExpiryDate AS JobExpiryDate,
PrintJobs.Batch,
PrintJobs.JulianDate AS JobJulianDate,
ProductMaster.Description,
ProductMaster.PackFormat,
ProductMaster.IngDec,
ProductMaster.BarCodeNumber,
ProductMaster.CustomerProductCode,
ProductMaster.CriticalInstruction,
ProductMaster.StorageInstruction,
ProductMaster.MixedCaseTitle,
ProductMaster.MixedCode1,
ProductMaster.MixedCode2,
ProductMaster.MixedCode3,
ProductMaster.MixedCode4,
ProductMaster.MixedDescription1,
ProductMaster.MixedDescription2,
ProductMaster.MixedDescription3,
ProductMaster.MixedDescription4,
ProductMaster.MixedIngDec1,
ProductMaster.MixedIngDec2,
ProductMaster.MixedIngDec3,
ProductMaster.MixedIngDec4,
ProductMaster.CookingInstruction,
ProductMaster.LogoFilename,
ProductMaster.ProductExpiryRule,
ExpiryRulesMaster.GS1_AppID,
ProductMaster.LabelTemplateID,
CASE WHEN ProductMaster.PartFileItemID IS NULL THEN 'N' ELSE 'Y' END AS LabelDefExists,
LabelTemplateMaster.FileName,
CASE WHEN [DateFormat] = 'Default' THEN ExpiryRulesMaster.DateFormatString ELSE [DateFormat] END AS DateFormatString,
ExpiryRulesMaster.DateRounding,
ExpiryRulesMaster.ExcludeXmasNewYear,
PART.ExternalShelfLifeTotalDays,
CustomOptions.Tagline,
CustomOptions.ShortName AS CustShortName,
ExpiryRulesMaster.LabelText AS ExpiryRuleLabelText,
ProductMaster.inner_hDescription,
ProductMaster.inner_vDescription,
ProductMaster.inner_CustCode,
ProductMaster.inner_Storage,
ProductMaster.inner_WarningMsg,
ProductMaster.inner_Dateformat,
ProductMaster.inner_SpecialCode,
ProductMaster.LabelType,
ProductMaster.inner_MicroSuiteCode,
ProductMaster.inner_PackWeight,
ProductMaster.inner_JDateFormat,
ProductMaster.CustomOptionID,
ProductMaster.inner_PrintLogo,
PART.NominalWeight,
ProductMaster.IngDec_html,
ProductMaster.IngDec_Active,
PrintJobs.PrintJobsID,
MaxJobs.MaxJob,
PrintJobs.DateEntered
FROM ProductMaster RIGHT OUTER JOIN
(
SELECT Partfileitemid,
--JobNumber,
MAX(dateentered) MaxJob
FROM PrintJobs
GROUP BY PartFileItemID
)
MaxJobs ON ProductMaster.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
PrintJobs ON PrintJobs.PartFileItemID = MaxJobs.PartFileItemID RIGHT OUTER JOIN
LabelTemplateMaster ON ProductMaster.LabelTemplateID = LabelTemplateMaster.LabelTemplateID LEFT OUTER JOIN
CustomOptions ON ProductMaster.CustomOptionID = CustomOptions.CustomOptionID LEFT OUTER JOIN
ExpiryRulesMaster ON ProductMaster.ProductExpiryRule = ExpiryRulesMaster.ExpiryRule LEFT OUTER JOIN
[F8Extract].[dbo].[WORDER] ON PrintJobs.WORDERKey = WORDER.WORDERKey LEFT OUTER JOIN
[F8Extract].[dbo].[PART] ON ProductMaster.PartFileItemID = Part.PartFileItemID
WHERE PrintJobs.WORDERKey = #WORDERKey
ORDER BY PrintJobs.Number DESC
Note change the PrintJobs.Number to whatever field specifies the time order.

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