【问题标题】:T-SQL: Update temp table using "from variable" queryT-SQL:使用“来自变量”查询更新临时表
【发布时间】:2015-09-05 14:19:59
【问题描述】:

我有一个链接服务器连接到作为源的 Lotus Notes 数据库。目标将是一个 MS 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 '+@tbl_name

UPDATE @temp_table

SET record_count = Execute(@sqlCommand)

END
CLOSE cur
Deallocate cur



select * from @temp_table

【问题讨论】:

  • 您使用哪种 RDBMS?
  • SSMS = SQL Server Management Studio 是 管理 GUI 应用程序 - 不是实际的 数据库系统 - 这可能 SQL Server 2012 - 或者它可能是不同的版本(因为管理 GUI 的版本不必与底层 SQL Server 核心引擎相同)
  • 我有一个链接服务器连接到 Lotus notes 数据库作为源。目标将是一个 MS SQL 数据库。

标签: sql while-loop sql-server-2012 cursor sql-update


【解决方案1】:

在执行中使用表变量并不容易,因为动态 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 '
        +@tbl_name+') where table_name = '''+@tbl_name+''')

【讨论】:

    猜你喜欢
    • 2017-11-26
    • 1970-01-01
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多