我如何避免使用動態從條款?即使我不知道數據庫的名字,我更喜歡使用靜態語句,就像這樣:避免使用從動態條款
select *
into #tempTable
from @DBName.Invoices
where InvoiceId = 5.
我得到這個錯誤:消息102,級別15,狀態1,行6 附近有語法錯誤''。
我需要使用 select into子句,因爲列名可能與每個數據庫不同;
謝謝!
我如何避免使用動態從條款?即使我不知道數據庫的名字,我更喜歡使用靜態語句,就像這樣:避免使用從動態條款
select *
into #tempTable
from @DBName.Invoices
where InvoiceId = 5.
我得到這個錯誤:消息102,級別15,狀態1,行6 附近有語法錯誤''。
我需要使用 select into子句,因爲列名可能與每個數據庫不同;
謝謝!
不幸的是,你將不得不使用動態SQL爲此,請參閱下面的例子
Declare @DBNAME NVARCHAR(MAX) = 'xxx'
Declare @SQL NVARCHAR(MAX) ='select *
into #tempTable
from ' + @DBName + '.Invoices
where InvoiceId = 5.'
execute sp_executesql @SQL
How can i avoid using dynamic from clause? Even if i don't know the database name, i prefer to use a static statement
SQL不會接受COLUMNNAMES,表名,databasenames作爲parameters.so除非你你避開他們,你不能避免動態SQL ..
查詢更改爲動態sql避免error..But再次你將有臨時表的範圍問題
- 這將失敗,becau SE臨時表屬於在不同範圍
Declare @sql nvarchar(4000)
set @sql='
select *
into #tempTable
from @DBName.Invoices
where InvoiceId = 5'
---一種選擇是使用全局臨時表
declare @dbname varchar(1000)
set @dbname=db_name()
declare @sql nvarchar(4000)
set @sql='select *
into ##tempTable
from '[email protected]+'.dbo.test_Delete '
exec(@sql)
select * from ##temptable
但要小心上面的方法,因爲上述臨時表具有全局作用域..
您還可以使用OPENROWSET,有些東西像下面
select * into #temp from openrowset
('SQLNCLI','Server=yourinstancename;Trusted_Connection=yes;', 'select * form table')
你到底想幹什麼?您無法使用動態SQL從變量中的對象中進行選擇。 –
不幸的是只有動態的sql會有所幫助。您可以創建自己的proc或使用不受支持的sp_MSforEachDB http://weblogs.sqlteam.com/joew/archive/2008/08/27/60700.aspx – Serg