简体   繁体   English

从动态表中选择

[英]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.我需要在 sql 中运行一个查询,这取决于我需要调用不同表的月份和年份。

For example:例如:

If current_date is 31/08/2020, execute: select * from table_ago如果 current_date 是 31/08/2020,执行:select * from table_ago

If current_date is 01/09/2020, execute: select * from table_sep如果 current_date 是 01/09/2020,执行:select * from table_sep

Is it posible using a query in SQL Server?是否可以在 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 :如果是这样,您可以使用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您可以使用存储过程和 if 条件来使这样的事情成为可能,如下所示

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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