This reply should have been posted in the comment, but it exceeded the number of words in the comment.
When the SQL statement has multiple or statements, you can consider using union or union all instead to improve speed. SQL statements using or often cannot be optimized, resulting in slower speeds. But this is not fixed, and sometimes it will be faster to use or. The specific situation is subject to testing.
As far as the readability of the code is concerned, if you really need so many filter conditions, the code can hardly be simplified.
Performance optimization issues, to be honest, we need to test according to our actual situation and some rules. However, it is often useful to build an index on the conditional column behind where (when there are multiple conditional columns, you can try compound index and covering index).
When you encounter a similar problem again, you can actually publish your needs and data directly, and the people on the forum will provide you with a variety of solutions, and you can choose the best method.Because when we can only see the code without understanding your actual needs and data, it may be difficult to give you good suggestions.
To use union all instead of or, please refer to the following code:
as(SELECT top 1 *
FROM extractreports.dbo.TblTemp T with(nolock) JOIN extractreports.dbo.Tbl_Temp TT with(nolock) ON T.GlobalPnID=TT.GlobalPnID
join (SELECT Max(GPNP.GroupID) GroupID,GPNP.GlobalPnID from dbo.GlobalPartNumberPortions GPNP with(nolock) group by GPNP.GlobalPnID ) K
on k.GroupID=t.GroupID and K.GlobalPnID =T.GlobalPnID
join extractreports.[dbo].[PCDataConfiguration] p with(nolock) on p.partnumber=t.[key]
left join extractreports.dbo.Tbl_TempCount tc with(nolock) on t.GlobalPnID =Tc.GlobalPnID
left join dbo.GlobalPartNumberPortionException gpnE with(nolock) on t.GlobalPnID =gpne.GlobalPnId
SELECT * FROM cte WHERE GlobalPnID is null
SELECT * FROM cte WHERE Counts =0
SELECT * FROM cte
WHERE (Counts >0 and [Key] like
CASE WHEN HasRange =1 THEN ExceptionRange
ELSE ExceptionSignature END
and 1= CASE WHEN HasRange =0 THEN 1
WHEN Exception like N'%~%'
If you do not have duplicate column names in several tables, you can refer to the above code. If there are duplicate column names, you need to name the aliases for the duplicate column names in cte.Because cte does not allow duplicate column names.