SQL Server : How to fetch data from dynamic multiple tables?

点点圈 提交于 2019-12-02 18:26:32

问题


Using SQL SERVER.

The database contains data from different years, somehow I want to fetch all the data (all the years) and show to the user, for example, database contains table:

table
--------
records_2000_01
records_2000_02
records_2000_03
...

now through select TABLE_NAME into @tableName from information_schema.tables where table_name like 'records_%'

I can fetch all the table name, how to write a SQL (or perhaps procedure) to fetch all data from these tables? make all record into one table?

thx.


回答1:


Create procedure in this Below steps you need to follow.

  • Create table Common_Table with same one structure which all your table like records_2000_02 and others.
  • Use loop or cursor for all records you get from information_schema which match your table name
  • Create dynamic sql like ' Insert into your Common_Table select * from ' + Table_name that you get from Information_schema.
    • Then you get all your data in one table Common_Table


来源:https://stackoverflow.com/questions/8524958/sql-server-how-to-fetch-data-from-dynamic-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!