declare @sql nvarchar(4000), @params nvarchar(4000) if @can_use_table1 = 1 select @sql= 'select abc from @table1' if @can_use_table2 = 1 begin if @can_use_table1 = 1 select @sql = @sql + ' intersect ' select @sql = @sql + 'select abc from @table2' end if @can_use_table3 = 1 begin if @can_use_table1 = 1 or @can_use_table2 = 1 select @sql= @sql + ' intersect ' select @sql= @sql + 'select abc from @table3' end if @can_use_table4 = 1 begin if @can_use_table1 = 1 or @can_use_table2 = 1 or @can_use_table3 = 1 select @sql= @sql + ' intersect ' select @sql= @sql + 'select abc from @table4' end select @params ='@can_use_table1 bit, @can_use_table2 bit, @can_use_table3 bit, @can_use_table4 bit, @table1 table, @table2 table, @table3 table, @table4 table' exec sp_executesql @sql,@params, @can_use_table1,@can_use_table2, @can_use_table3, @can_use_table4, @table1, @table2, @table3, @table4
source share