简体   繁体   中英

Select from dynamic table

I need to run a query in sql that depending on the month and year I need to call a different table.

For example:

If current_date is 31/08/2020, execute: select * from table_ago

If current_date is 01/09/2020, execute: select * from table_sep

Is it posible using a query in SQL Server?

This is only possible in a non-dynamic query if the two tables have the sample columns. If so, you can use union all :

select *
from table_ago
where convert(date, getdate()) = '2020-08-31'
union all
select *
from table_sep
where convert(date, getdate()) = '2020-09-01';

If the tables have different columns, then you probably need to use a stored procedure . . . but it would be hard to use the results in a query.

You can use a stored procedure and if condition to make possible such a thing like following

create procedure spCheckTable
@date date   --create variable to enter date as parameter
as begin
    declare @toBeCheckDate date = (select top 1 date_column from BaseTable) --create variable to store date from table
    if @toBeCheckDate = @date
        begin
            select * from table_ago
        end
    else if @toBeCheckDate = @date
        begin
            select * from table_sep
        end
end

Now run the procedure like follow

execute spCheckTable '2020-09-02'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM