[英]Select from dynamic table
我需要在 sql 中运行一个查询,这取决于我需要调用不同表的月份和年份。
例如:
如果 current_date 是 31/08/2020,执行:select * from table_ago
如果 current_date 是 01/09/2020,执行:select * from table_sep
是否可以在 SQL Server 中使用查询?
如果两个表都有示例列,这仅在非动态查询中是可能的。 如果是这样,您可以使用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 条件来使这样的事情成为可能,如下所示
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
现在运行如下程序
execute spCheckTable '2020-09-02'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.