Combine Queries using Union All Dynamically












0















I have three tables:



    Table A                  Table B                     Table C
______________ ______________ ______________
| Order | Year | | Order | Year | | Order | Year |
+--------------+ +--------------+ +--------------+
| O1-17 | 2017 | | O1-18 | 2018 | | O1-19 | 2019 |
+--------------+ +--------------+ +--------------+


I combined those tables using UNION ALL.



SELECT Order,Year FROM [Table A]
UNION ALL
SELECT Order,Year FROM [Table B]
UNION ALL
SELECT Order,Year FROM [Table C]


My problem is, each year there is a new table to be added. One example is that Table D with corresponding record Order O1-20 and Year 2020. Instead of adding another set of UNION ALL, is there any other way to achieve the same result.










share|improve this question


















  • 2





    Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

    – Dale Burrell
    Nov 20 '18 at 1:19











  • Yes, I have to. I just simplified my example. Actually each table is in different databases.

    – Rigel1121
    Nov 20 '18 at 1:21











  • Is it for reporting purposes?

    – Dale Burrell
    Nov 20 '18 at 1:22











  • yes. it is for reporting purposes.

    – Rigel1121
    Nov 20 '18 at 1:23






  • 1





    dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

    – peeyush singh
    Nov 20 '18 at 1:35


















0















I have three tables:



    Table A                  Table B                     Table C
______________ ______________ ______________
| Order | Year | | Order | Year | | Order | Year |
+--------------+ +--------------+ +--------------+
| O1-17 | 2017 | | O1-18 | 2018 | | O1-19 | 2019 |
+--------------+ +--------------+ +--------------+


I combined those tables using UNION ALL.



SELECT Order,Year FROM [Table A]
UNION ALL
SELECT Order,Year FROM [Table B]
UNION ALL
SELECT Order,Year FROM [Table C]


My problem is, each year there is a new table to be added. One example is that Table D with corresponding record Order O1-20 and Year 2020. Instead of adding another set of UNION ALL, is there any other way to achieve the same result.










share|improve this question


















  • 2





    Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

    – Dale Burrell
    Nov 20 '18 at 1:19











  • Yes, I have to. I just simplified my example. Actually each table is in different databases.

    – Rigel1121
    Nov 20 '18 at 1:21











  • Is it for reporting purposes?

    – Dale Burrell
    Nov 20 '18 at 1:22











  • yes. it is for reporting purposes.

    – Rigel1121
    Nov 20 '18 at 1:23






  • 1





    dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

    – peeyush singh
    Nov 20 '18 at 1:35
















0












0








0








I have three tables:



    Table A                  Table B                     Table C
______________ ______________ ______________
| Order | Year | | Order | Year | | Order | Year |
+--------------+ +--------------+ +--------------+
| O1-17 | 2017 | | O1-18 | 2018 | | O1-19 | 2019 |
+--------------+ +--------------+ +--------------+


I combined those tables using UNION ALL.



SELECT Order,Year FROM [Table A]
UNION ALL
SELECT Order,Year FROM [Table B]
UNION ALL
SELECT Order,Year FROM [Table C]


My problem is, each year there is a new table to be added. One example is that Table D with corresponding record Order O1-20 and Year 2020. Instead of adding another set of UNION ALL, is there any other way to achieve the same result.










share|improve this question














I have three tables:



    Table A                  Table B                     Table C
______________ ______________ ______________
| Order | Year | | Order | Year | | Order | Year |
+--------------+ +--------------+ +--------------+
| O1-17 | 2017 | | O1-18 | 2018 | | O1-19 | 2019 |
+--------------+ +--------------+ +--------------+


I combined those tables using UNION ALL.



SELECT Order,Year FROM [Table A]
UNION ALL
SELECT Order,Year FROM [Table B]
UNION ALL
SELECT Order,Year FROM [Table C]


My problem is, each year there is a new table to be added. One example is that Table D with corresponding record Order O1-20 and Year 2020. Instead of adding another set of UNION ALL, is there any other way to achieve the same result.







sql sql-server






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 1:16









Rigel1121Rigel1121

1,79511122




1,79511122








  • 2





    Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

    – Dale Burrell
    Nov 20 '18 at 1:19











  • Yes, I have to. I just simplified my example. Actually each table is in different databases.

    – Rigel1121
    Nov 20 '18 at 1:21











  • Is it for reporting purposes?

    – Dale Burrell
    Nov 20 '18 at 1:22











  • yes. it is for reporting purposes.

    – Rigel1121
    Nov 20 '18 at 1:23






  • 1





    dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

    – peeyush singh
    Nov 20 '18 at 1:35
















  • 2





    Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

    – Dale Burrell
    Nov 20 '18 at 1:19











  • Yes, I have to. I just simplified my example. Actually each table is in different databases.

    – Rigel1121
    Nov 20 '18 at 1:21











  • Is it for reporting purposes?

    – Dale Burrell
    Nov 20 '18 at 1:22











  • yes. it is for reporting purposes.

    – Rigel1121
    Nov 20 '18 at 1:23






  • 1





    dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

    – peeyush singh
    Nov 20 '18 at 1:35










2




2





Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

– Dale Burrell
Nov 20 '18 at 1:19





Do you have to create a new table each year? Not good practice. Otherwise only option is to use dynamic SQL.

– Dale Burrell
Nov 20 '18 at 1:19













Yes, I have to. I just simplified my example. Actually each table is in different databases.

– Rigel1121
Nov 20 '18 at 1:21





Yes, I have to. I just simplified my example. Actually each table is in different databases.

– Rigel1121
Nov 20 '18 at 1:21













Is it for reporting purposes?

– Dale Burrell
Nov 20 '18 at 1:22





Is it for reporting purposes?

– Dale Burrell
Nov 20 '18 at 1:22













yes. it is for reporting purposes.

– Rigel1121
Nov 20 '18 at 1:23





yes. it is for reporting purposes.

– Rigel1121
Nov 20 '18 at 1:23




1




1





dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

– peeyush singh
Nov 20 '18 at 1:35







dynamic sql and cursors, I have worked on similar new tables", no way to delete so I might complete the comment....you can create empty new tables/database for next 20 years and just put in an error somewhere that its 2038 please create new tables! If you are for dynamic sql, its fairly easy just build the normal sql as string and then execute: mssqltips.com/sqlservertip/1160/…

– peeyush singh
Nov 20 '18 at 1:35














1 Answer
1






active

oldest

votes


















1














You have 3 options that I can think of:



1) Manually update the union in your query each year - not ideal but probably better than option 2.



2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.



3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.





Option 2 might look like:



declare @StartYear int = 2015, @EndYear int = datepart(year, getdate()), @sql nvarchar(max) = '', @Index int;
set @Index = @StartYear;

declare @Years table ([Name] varchar(128));

while @Index <= @EndYear begin
insert into @Years ([Name])
select 'BaseTableName' + convert(varchar, @Index);
set @Index = @Index+1;
end

select @sql = @sql + case when len(@sql) > 0 then ' union all ' else '' end + 'select [Order], [Year] from ' + [Name]
from @Years

select @sql
--exec(@sql)





share|improve this answer


























  • For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

    – Rigel1121
    Nov 20 '18 at 1:33











  • @Rigel1121 I've added code for option 2 which should be enough to get you started.

    – Dale Burrell
    Nov 20 '18 at 1:42













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384889%2fcombine-queries-using-union-all-dynamically%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









1














You have 3 options that I can think of:



1) Manually update the union in your query each year - not ideal but probably better than option 2.



2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.



3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.





Option 2 might look like:



declare @StartYear int = 2015, @EndYear int = datepart(year, getdate()), @sql nvarchar(max) = '', @Index int;
set @Index = @StartYear;

declare @Years table ([Name] varchar(128));

while @Index <= @EndYear begin
insert into @Years ([Name])
select 'BaseTableName' + convert(varchar, @Index);
set @Index = @Index+1;
end

select @sql = @sql + case when len(@sql) > 0 then ' union all ' else '' end + 'select [Order], [Year] from ' + [Name]
from @Years

select @sql
--exec(@sql)





share|improve this answer


























  • For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

    – Rigel1121
    Nov 20 '18 at 1:33











  • @Rigel1121 I've added code for option 2 which should be enough to get you started.

    – Dale Burrell
    Nov 20 '18 at 1:42


















1














You have 3 options that I can think of:



1) Manually update the union in your query each year - not ideal but probably better than option 2.



2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.



3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.





Option 2 might look like:



declare @StartYear int = 2015, @EndYear int = datepart(year, getdate()), @sql nvarchar(max) = '', @Index int;
set @Index = @StartYear;

declare @Years table ([Name] varchar(128));

while @Index <= @EndYear begin
insert into @Years ([Name])
select 'BaseTableName' + convert(varchar, @Index);
set @Index = @Index+1;
end

select @sql = @sql + case when len(@sql) > 0 then ' union all ' else '' end + 'select [Order], [Year] from ' + [Name]
from @Years

select @sql
--exec(@sql)





share|improve this answer


























  • For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

    – Rigel1121
    Nov 20 '18 at 1:33











  • @Rigel1121 I've added code for option 2 which should be enough to get you started.

    – Dale Burrell
    Nov 20 '18 at 1:42
















1












1








1







You have 3 options that I can think of:



1) Manually update the union in your query each year - not ideal but probably better than option 2.



2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.



3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.





Option 2 might look like:



declare @StartYear int = 2015, @EndYear int = datepart(year, getdate()), @sql nvarchar(max) = '', @Index int;
set @Index = @StartYear;

declare @Years table ([Name] varchar(128));

while @Index <= @EndYear begin
insert into @Years ([Name])
select 'BaseTableName' + convert(varchar, @Index);
set @Index = @Index+1;
end

select @sql = @sql + case when len(@sql) > 0 then ' union all ' else '' end + 'select [Order], [Year] from ' + [Name]
from @Years

select @sql
--exec(@sql)





share|improve this answer















You have 3 options that I can think of:



1) Manually update the union in your query each year - not ideal but probably better than option 2.



2) Use dynamic SQL to build the query and it can automatically build the query based on the date the query is run. Its a bit ugly thought and performance might not be great.



3) This would be my preferred option, run a regular maintenance task to populate a completely separate table, in a single database, with just the data required for the report.





Option 2 might look like:



declare @StartYear int = 2015, @EndYear int = datepart(year, getdate()), @sql nvarchar(max) = '', @Index int;
set @Index = @StartYear;

declare @Years table ([Name] varchar(128));

while @Index <= @EndYear begin
insert into @Years ([Name])
select 'BaseTableName' + convert(varchar, @Index);
set @Index = @Index+1;
end

select @sql = @sql + case when len(@sql) > 0 then ' union all ' else '' end + 'select [Order], [Year] from ' + [Name]
from @Years

select @sql
--exec(@sql)






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 '18 at 1:41

























answered Nov 20 '18 at 1:27









Dale BurrellDale Burrell

3,17132451




3,17132451













  • For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

    – Rigel1121
    Nov 20 '18 at 1:33











  • @Rigel1121 I've added code for option 2 which should be enough to get you started.

    – Dale Burrell
    Nov 20 '18 at 1:42





















  • For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

    – Rigel1121
    Nov 20 '18 at 1:33











  • @Rigel1121 I've added code for option 2 which should be enough to get you started.

    – Dale Burrell
    Nov 20 '18 at 1:42



















For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

– Rigel1121
Nov 20 '18 at 1:33





For me, the better option is number 2. And I'm researching for stored procedures with cursor, but I can't figure out on how to do it.

– Rigel1121
Nov 20 '18 at 1:33













@Rigel1121 I've added code for option 2 which should be enough to get you started.

– Dale Burrell
Nov 20 '18 at 1:42







@Rigel1121 I've added code for option 2 which should be enough to get you started.

– Dale Burrell
Nov 20 '18 at 1:42




















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53384889%2fcombine-queries-using-union-all-dynamically%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

How to change which sound is reproduced for terminal bell?

Can I use Tabulator js library in my java Spring + Thymeleaf project?

Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents