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)
这篇关于从视图中的动态表名中选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从视图中的动态表名中选择
基础教程推荐
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在多列上分布任意行 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- oracle区分大小写的原因? 2021-01-01
