Answer the question
In order to leave comments, you need to log in
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
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.
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)
CREATE SYNONYM [dbo].[very_strong_table_20170109] FOR [dbo].[very_strong_table_all]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question