2015-06-19 60 views
1

我有一個鏈接服務器連接到Lotus Notes數據庫作爲源。目標將是一個MS SQL數據庫。T-SQL:使用「從變量」查詢更新臨時表

我有兩個臨時表。第一個臨時表從連接的服務器拉入表名。從那裏,我想爲每個表執行一次記錄計數,並將該值存儲到表名旁邊的第二個臨時表中。

我無法嘗試爲每個表名稱運行循環或遊標,然後使用每個表名稱的記錄計數更新第二個臨時表。

現在我得到一個錯誤「Execute'附近語法不正確」。 SET record_count = Execute(@sqlCommand)

Declare @DB_tables table (
table_cat varchar(1500), 
table_schem varchar(1500), 
table_name varchar(1500), 
table_type varchar(1500), 
remarks varchar(1500) 
) 


Declare @temp_table table (
table_name varchar(1500), 
record_count varchar(255), 
drop_script varchar(1500), 
update_script varchar(1500) 
) 

--Load Initial data from linked server database 
insert into @DB_Tables 
exec sp_tables_ex [LINKED_SERVER_DB] 

--Load table name from Stored Procedure 
INSERT INTO @temp_table (table_name) 
SELECT table_name from @DB_Tables 

--select * from @temp_table 




--Variable to hold each table name in a loop or cursor 
declare @tbl_name varchar(1500) 
--declare @sqlCommand varchar(1500) 


declare cur cursor for select table_name from @DB_Tables 
Open cur 

--Loop through each table name from the first temp table 
--then update the second temp table (@temp_table) with the record count 
FETCH NEXT FROM cur into @tbl_name 

While @@FETCH_STATUS = 0 BEGIN 

declare @sqlCommand varchar(1500) 
--query used to get the record count from the frist temp table (@DB_tables) 
SET @sqlCommand = 'select count(*) from '[email protected]_name 

UPDATE @temp_table 

SET record_count = Execute(@sqlCommand) 

END 
CLOSE cur 
Deallocate cur 



select * from @temp_table 
+0

你使用哪種RDBMS? –

+0

SSMS 2012(32位) –

+0

SSMS = SQL Server Management Studio是**管理GUI **應用程序 - 不是實際的**數據庫系統** - 這可能是SQL Server 2012 - 或者它可能是不同的版本(因爲管理GUI的版本與底層SQL Server **核心引擎**無關) –

回答

0

這是不容易的使用表變量與執行,因爲動態SQL是在不同的上下文中執行,並沒有看到變化,你不能從指定執行這樣的結果。

您可以將結果插入使用這種語法表變量:

insert into @temp_table 
execute ('select ' + @tbl_name + ', count(*) from ' + @tbl_name ...) 

或者使用溫度。表,因爲那時你可以在動態SQL裏面引用它們,所以你可以這樣做:

create table #temp_table (
table_name varchar(1500), 
record_count varchar(255), 
drop_script varchar(1500), 
update_script varchar(1500) 
) 
... 
Execute('update #temp_table set record_count = (select count(*) from ' 
     [email protected]_name+') where table_name = '''[email protected]_name+''')