declare @from varchar(1000) = ' sales.SalesOrderHeader sh with(nolock) join sales.SalesOrderDetail sd with(nolock) on sh.SalesOrderID = sd.SalesOrderID join Production.Product pp with(nolock) on sd.ProductID = pp.ProductID join Production.ProductModel ppm with(nolock) on pp.ProductModelID = ppm.ProductModelID join Production.ProductSubcategory pps with(nolock) on pp.ProductSubcategoryID = pps.ProductSubcategoryID join Production.ProductCategory ppc with(nolock) on pps.ProductCategoryID = ppc.ProductCategoryID join sales.Customer sc with(nolock) on sh.CustomerID = sc.CustomerID join person.[Address] pa with(nolock) on sh.ShipToAddressID = pa.AddressID '
declare @basicCondition varchar(1000) = ' sh.ShipDate between @begDate and @endDate and sh.[Status] = 5'
if OBJECT_ID('tempdb..#Conditions') is not null drop table #Conditions create table #Conditions ( ConditionID int identity(1,1) primary key, Name varchar(100), [Text] varchar(200), [Value] varchar(200) ) insert #Conditions(Name, [Text], [Value]) select ' ', 'pa.city in (''Berlin'', ''Bonn'') and ppc.Name in (''Byke'')' , 'sd.OrderQty * pp.Weight' insert #Conditions(Name, [Text], [Value]) select ' ', 'pa.city in (''Berlin'', ''Bonn'') and ppc.Name not in (''Byke'')', 'sd.OrderQty * pp.Weight' insert #Conditions(Name, [Text], [Value]) select ' ', 'pa.city not in (''Berlin'', ''Bonn'')', 'sd.OrderQty * pp.Weight'
select <>, Errors = iif(<1>,<1>,'') + ', ' + iif(<2>,<2>,'') +… from < FROM> where ( <> ) and ( 1 <> iif(<1>,1,0) + iif(<2>,1,0)+… )
Select <…> From < FROM> Cross apply ( Select id = <1>, price = <Price1>, value = <1> where <1> Union all Select id = <2>, price = <Price2>, value = <2> where <2> …. ) Services Where <>
Select service = case When <1> then <1> When <2> then <2> When <3> then <3> … When 1=1 then null End, < > From < FROM> Where <>
declare @sql varchar(max) select @sql = case when @sql is null then '' else @sql + char(10) + ' union all '+char(10) end -- SELECT- UNION ALL + ' select ConditionID = '+convert( varchar(10), ConditionID )+', [Value] = ('+chk.Value+') where ' + chk.Condition from #Conditions outer apply ( select -- - , [Condition] = case when [text] <> '' then [text] else '1<>1' end , [Value] = case when [Value] <> '' then [Value] else 'null' end ) chk If @sql is null set @sql = ' select ConditionID = null, [Value] = null where 1<>1 ' drop table #Conditions -- declare @template varchar(max) = ' create procedure #exec_calc (@begDate datetime, @endDate datetime ) as begin select sh.SalesOrderID, calc.ConditionID, Value = sum( Calc.Value) from <FROM> cross apply (<CONDITIONS>) Calc where ( <BASIC_CONDITIONS> ) group by sh.SalesOrderID, calc.conditionID end' set @sql = replace(@template, '<CONDITIONS>' , @sql) set @sql = replace(@sql , '<FROM>' , @from) set @sql = replace(@sql , '<BASIC_CONDITIONS>', @basicCondition) print @sql –- . )) -- execute( @sql ) -- AdventureWorks2008R2 exec #exec_calc ''20071001'', ''20071031''
Source: https://habr.com/ru/post/270363/
All Articles