Link to home
Start Free TrialLog in
Avatar of BananaFury
BananaFury

asked on

Looping with SQL

Hello

I want to run a very quick query against a table (1)
From this table I would like to extract some key records, and insert them into a new table (x)
I would then like to repeat this process on the next table (2) and repeat until I am out of tables.
The tables are all named with the date they were created as follows:
tbl_Table_2014_12_15
tbl_Table_2014_12_14
tbl_Table_2014_12_13
tbl_Table_2014_12_12

Is this something I am able to do with SQL?

Thanks
Avatar of Vikas Garg
Vikas Garg
Flag of India image

Hi,

You can do this with While Loop.

Take Temp table store table name into it
Assign count of that table to variable and in the loop assign table names to another variable

In the query side perform dynamic query passing source and destination table

Hope this will help you
Avatar of BananaFury
BananaFury

ASKER

Hello,

Thanks very much for your replies.

I confess, I am modest with SQL at best. Could you please provide me with an example of the code required for my particular scenario?

Thanks
my article has sample code, only you need to fill in the part of the sql that you need
your explanation is vague, so providing some "end code" will not be possible...
as a side note, your requirement looks like you may actually need to step back and check if for example a partitioned table is the better/faster option in regards what you may need to do.
so, question 1: what is the process about, actually (why do you want to implement this)
question 2: please clarify what data should go from where to where exactly, and what about existing data etc...
Hello,

Thanks for your help.
I want to go through each of the tables and pull from them all of the Open records. These records I would like to place in a separate table that contains only the Open records, but from each table (which is a point in time)

Below is the only way I know how to tackle such a task. We have 3 years of tables though, so 1000+ tables so I suspect there is an easier way of doing this.


INSERT INTO tbl_All_Open_Records
SELECT *
FROM tbl_Table_2014_12_15 WHERE [Status] = 'Open'

INSERT INTO tbl_All_Open_Records
SELECT *
FROM tbl_Table_2014_12_14 WHERE [Status] = 'Open'

INSERT INTO tbl_All_Open_Records
SELECT *
FROM tbl_Table_2014_12_13 WHERE [Status] = 'Open'

..... etc
SOLUTION
Avatar of Simon
Simon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks very much for all of your help