Advertisement
anchormodeling

Consolidate Execution Plan Paths

Sep 10th, 2013
8,455
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 1.71 KB | None | 0 0
  1. -- if accidentally left on from previous runs
  2. SET STATISTICS XML OFF;
  3. SET STATISTICS IO,TIME OFF;
  4.  
  5. -- which version?
  6. select @@VERSION;
  7.  
  8. -- drop if they exist
  9. drop view lAN;
  10. drop view vAt2;
  11. drop table At2;
  12. drop table AN;
  13.  
  14. -- create the tables
  15. create table AN (
  16.     id int not null primary key
  17. );
  18.  
  19.  
  20. create table At2 (
  21.     id int not null foreign key references AN(id),
  22.     stamp datetime not null,
  23.     primary key (
  24.         id,
  25.         stamp
  26.     )
  27. );
  28. go
  29.  
  30. -- create a view
  31. create view vAt2
  32. as
  33. select 
  34.     id,
  35.     stamp,
  36.     ROW_NUMBER() over (
  37.         partition by
  38.             id
  39.         order by
  40.             stamp desc
  41.     ) as v
  42. from
  43.     At2
  44. go
  45.  
  46. create view lAN
  47. as
  48. with a2 as (
  49.     select
  50.         *
  51.     from
  52.         vAt2
  53.     where
  54.         v = 1
  55. )
  56. select
  57.     an.id as AN_id,
  58.     (select id from a2 where a2.id = an.id) as AT2_id,
  59.     (select stamp from a2 where a2.id = an.id) as AT2_stamp,
  60.     (select stamp from a2 where a2.id = an.id) as AT2_stamp_again
  61. from
  62.     AN an;
  63. go
  64.  
  65. -- populate the tables
  66. declare @numberOfRows int = 1000;
  67.  
  68. with rowGen(rowNum) as (
  69.     select
  70.         1
  71.     union all
  72.     select
  73.         rowNum + 1
  74.     from
  75.         rowGen
  76.     where
  77.         rowNum < @numberOfRows
  78. )
  79. insert into AN (id)
  80. select rowNum from rowGen
  81. option (maxrecursion 0);
  82.  
  83. declare @now datetime = getdate();
  84. declare @then datetime = dateadd(day, -333, @now);
  85.  
  86. insert into At2 (id, stamp) select id, @now from AN;
  87. insert into At2 (id, stamp) select id, @then from AN;
  88. go
  89.  
  90. SET STATISTICS XML ON;
  91. SET STATISTICS IO,TIME ON;
  92. -------------------------------------------------------------
  93. select
  94.     avg(cast(AT2_id as bigint)),
  95.     min(AT2_stamp),
  96.     min(AT2_stamp_again)
  97. from
  98.     lAN
  99. where
  100.     AT2_id is not null;
  101. -------------------------------------------------------------
  102. SET STATISTICS XML OFF;
  103. SET STATISTICS IO,TIME OFF;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement