Good day and welcome to the QnA forum,
The query works correctly but I want to do something dynamic without filter in IdProd in the last query
What do you want to get in this query? Why did you selected specific IdProd in the first place?
Your requirement is not clear
we have an exception with Id_Prod = 7200
Yu explicitly say that you have exception which this specific Id_Prod. So , what do you need to do dynamic here?
Please try to clarify and in the mean time, you do not need to use the first two queries and read the table twice. The first two queries can be merged into simple one, using the condition: where (DateManu >= Begin_valid and DateLIV <End_valid) or (IdProd is null)
select IdProd,DateManu,DateLIV,Status
from Fact_Manufacturing
left join Dim_ProductStatusHistory on id_product=IdProd
where (DateManu >= Begin_valid and DateLIV <End_valid) or (IdProd is null)
union
select
IdProd, ISNULL(lead(Begin_valid) over(partition by idProd order by Begin_valid),DateManu) as DateManu,
isnull(lag(End_valid) over(partition by idProd order by End_valid),DateLIV) as DateLIV,Status
from Fact_Manufacturing
left join Dim_ProductStatusHistory on id_product=IdProd
where IdProd=7200