本文介紹了從視圖中的動態表名中選擇的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我的客戶每年都會創建一個新表,其中的年份包含在我必須在我的 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)
這篇關于從視圖中的動態表名中選擇的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!