Select from a dynamic table name in a view(从视图中的动态表名中选择)
问题描述
我的客户每年都会创建一个新表,其中的年份包含在我必须在我的 SQL Server 数据库的新视图中使用的名称中.我已经在一个查询中解决了这个问题:
My customer creates yearly a new table with the year included in the name that I have to use in a new view of my SQL Server database. I have solved this problem in a single query:
DECLARE @SQLString nvarchar(500)
SET @SQLString = 'SELECT * FROM [MYDATABASE].[dbo].[MYTABLE_'+cast(YEAR(GETDATE()) as varchar(4))+']'
EXECUTE sp_executesql @SQLString
但我不能在视图中使用执行语句.我也尝试将它移动到一个函数,但问题是一样的.¿我能做什么?
but I cannot use an execute statement in a view. I've also tryied to move it to a function but the problem is the same. ¿What could I do?
提前致谢.
推荐答案
我不知道它是否适合您,但您可以动态创建视图本身.像这样:
I don't know if it is an option for you, but you can dynamically create a view itself. Something like this:
declare @sql varchar(1000)
,@sql2 varchar(1000)
set @sql = ('create view x as select * from MyTable_' + convert(varchar(10),year(getdate())) + ' go')
set @sql2 = 'select * from x'
exec (@sql)
exec (@sql2)
这篇关于从视图中的动态表名中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从视图中的动态表名中选择
基础教程推荐
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
