Skip to content
Advertisement

get all the tables within a date range

I have many weekly backup tables of the same structure and columns but with different names containing some user-specific information like this.

Now I want to find the tables within a date range for example: If I choose the date range of 2021-11-20 to 2021-11-13 then the tables fetched would be user_details, user_details_20211126, user_details_20211119 for using them in a query containing union operation on all the fetched tables. Any idea on how to do that?

Advertisement

Answer

As already commented, what an awful idea … you shouldn’t be doing it that way. One table with a DATE datatype column should by the way to do it. I suggest you switch to it – the sooner, the better.


Meanwhile – although you didn’t name database you use & I’m using Oracle – here’s what you’ll probably have to do, regardless of the database: some kind of dynamic SQL as you have to “dynamically” compose the SELECT statement, using only tables that satisfy the condition. As you have to fetch their names from the data dictionary, you don’t have many options but – as I said – dynamic SQL.

OK, here you go.

Setting date format (you don’t have to do that):

Tables whose names are user_details_something:

How to select only tables whose name contains date that is between desired values?

  • query data dictionary (in Oracle, that’s user_tables)
  • extract the DATE part of their names (I chose regexp_substr function; you’d use any you find appropriate)
  • convert extracted substring into a valid date value (using TO_DATE function)

Therefore:

OK; two tables between 26.11.2021 and 27.11.2021 (I didn’t feel like creating more of them).


The second part of the job is to actually fetch data from those tables. Here’s a function that accepts date period as parameters and returns ref cursor (you can choose something else, of course). Read comments within code:

OK, let’s try it:


It works for me; I hope you won’t have to make it “work” at all, but – after you apply what we’ve already suggested – run a simple

Obviously, my user_details table contains the DATE datatype column and makes everything A LOT simpler.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement