J
J
Jozo2018-10-17 23:04:23
SQL
Jozo, 2018-10-17 23:04:23

How to create a query in MSSQL for output from several tables?

You need to display data from all tables that look like:
very_strong_table_20170109
very_strong_table_20170209
very_strong_table_20170308
very_strong_table_20170407
very_strong_table_20170506
The very_strong_table_******** table is created every month (30 days). They have the same structure.
I would appreciate any advice, thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Tsvetkov, 2018-10-18
@Jozo

Use UNION, generate a query dynamically.
List of tables:
Based on it, form a request.
Because you were taught. I would use a cursor, I'm used to them.

for example
DECLARE @TAB VARCHAR(500), @SQL VARCHAR(1000)
  SET @SQL = '--'
  DECLARE LISTTABLEE CURSOR LOCAL FAST_FORWARD FOR
    SELECT name FROM sysobjects WHERE name like 'very_strong_table_%' AND type = 'U'
  OPEN LISTTABLEE
  FETCH LISTTABLEE INTO @TAB
  WHILE @@FETCH_STATUS = 0 BEGIN
    SET @SQL = @SQL + CHAR(13)+CHAR(10)+'SELECT * FROM '+ @TAB
    FETCH LISTTABLEE INTO @TAB
    IF @@FETCH_STATUS = 0 
      SET @SQL = @SQL + CHAR(13)+CHAR(10)+'UNION'
  END
  CLOSE LISTTABLEE
  DEALLOCATE LISTTABLEE
  PRINT @SQL
  EXECUTE(@SQL)
docs.microsoft.com
Note: Using multiple tables instead of just one is a very big mistake. Especially if the tables have the same parameters, for example, they are in the same file.
There are several possible solutions here. For example, make a view containing a UNION from a list of tables. Or to create most one table , and to palm off synonyms to application.
CREATE SYNONYM  [dbo].[very_strong_table_20170109] FOR [dbo].[very_strong_table_all]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question