Hi @ahmed salah ,
if you face this kind of issue, you could consider different conditions when you would like to concatenate one string.
What is the expected output of @ConStr if EStrat is 'N/A' or NULL?
Please refer below example:
DECLARE @Sql nvarchar(max)
DECLARE @ConStr nvarchar(max)
SET @ConStr= STUFF((SELECT CONCAT(' Or (PM.ZfeatureKey= ', CC.ZfeatureKey , ' And '+
case when PATINDEX('%[><=]%', EStrat)>0 then
'AcceptedValuesOption_Value '
when EStrat is null then
'cast(AcceptedValuesOption_Value as varchar(100)) '
else
'cast(AcceptedValuesOption_Value as varchar(100))='
end,
case when PATINDEX('%[><=]%', EStrat)>0 then
CAST(EStrat AS NVARCHAR(2500))
when EStrat is null then
' is null '
else
''''+CAST(EStrat AS NVARCHAR(2500)) +''''
end
, IIF(EEnd='','',CONCAT(' And AcceptedValuesOption_Value ',EEnd)),')')
FROM #Condition CC INNER JOIN #Allfeatures AL ON AL.ZfeatureKey = CC.ZfeatureKey
FOR XML PATH(''), TYPE).value('(./text())[1]','varchar(max)'),1,3,'')
---EXE(@ConStr)
--print @ConStr
SET @Sql= CONCAT(' SELECT PartID, Code, Count(1) as ConCount
FROM #PartAttributes PM
INNER JOIN #Condition Co ON Co.ZfeatureKey = PM.ZfeatureKey ',
'Where 1=1 and (', @ConStr, ' ) Group By PartID,Code ' ,
' Having Count(1)> = ',(SELECT COUNT(1) FROM #Condition))
--print @SQL
EXEC (@SQL)
If you have any other issue, please provide more sample data and expected output.
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.