2015-06-19 52 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+''')