[英]T-SQL: Update temp table using “from variable” query
我有一個鏈接服務器,連接到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
將表變量與execute一起使用並不容易,因為動態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+''')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.