Advertisement
jchaven

Create numbers and calendar tables

Jan 6th, 2012
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MySQL 0.91 KB | None | 0 0
  1. -- Numbers and Calendar tables to make certain queries easier
  2. -- See: http://stackoverflow.com/a/5123255
  3.  
  4. use dbMain;
  5.  
  6. -- create digits table
  7. create table digits(n int);
  8. insert into digits values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);
  9.  
  10. create table numbers(
  11.    n int not null
  12.   ,primary key(n)
  13. );
  14.  
  15.  
  16. -- create numbers table
  17. insert
  18.   into numbers(n)
  19. select 1
  20.       + (d1.n * 1)
  21.       + (d2.n * 10)
  22.       + (d3.n * 100)
  23.       + (d4.n * 1000)
  24.       + (d5.n * 10000)
  25.       + (d6.n * 100000) as n
  26.   from digits d1
  27.       ,digits d2
  28.       ,digits d3
  29.       ,digits d4
  30.       ,digits d5
  31.       ,digits d6;
  32.  
  33. -- drop the working table
  34. drop table digits;
  35.  
  36.  
  37. -- create calendar table
  38. create table calendar(
  39.    datum date not null
  40.   ,primary key(datum)
  41. );
  42.  
  43.  
  44. -- populate calendar table
  45. insert
  46.   into calendar(datum)
  47. select date_add('1999-12-31', interval n day)
  48.   from numbers
  49.  where n <=8000;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement