我有一個使用臨時表的腳本。當我與服務器斷開連接、連接并運行腳本時,它按預期作業。如果我兩次運行相同的腳本,它第一次作業,然后在第二次,抱怨;
Column name or number of supplied values does not match table definition.
我相信我在下面明確洗掉了表格。我還在腳本的開頭drop table為臨時表添加了一些額外的命令作為很好的衡量標準。如何確保洗掉臨時表,以便該程序可重復?
-- create table of differences
drop table if exists #TMP;
select A.*,'table A' TABLE_NAME INTO #TMP from #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );
INSERT INTO #TMP -- FAILS ON THIS LINE; only one the second try!
select B.*,'table B' from #compare1 a
full outer join #compare2 b on a.hash = b.hash
where ( a.hash is null or b.hash is null );
uj5u.com熱心網友回復:
洗掉腳本末尾而不是開頭的表。
如果您必須在開頭洗掉它,請在GO之后放置一個,drop table if exists以便在嘗試編譯腳本的其余部分之前,它會在自己的批處理中運行。
還要考慮使用更具體的名稱#TMP- 看起來必須在父作用域中創建該表名的另一個實體,該實體在編譯批處理并導致錯誤時可見。(或者您正在更改您未向我們展示的代碼中的表架構)
uj5u.com熱心網友回復:
如果我想在 SQL Server management Studio 的查詢視窗中多次運行它,我通常會執行以下操作。如果在運行第二個之前存在臨時表,這將始終洗掉它。
IF EXISTS (SELECT * FROM tempdb.dbo.sysobjects O WHERE O.xtype in ('U') AND O.id = object_id(N'tempdb..#MyTempTable'))
BEGIN
PRINT 'Removing temp table #MyTempTable'
DROP TABLE #MyTempTable;
END
CREATE TABLE #MyTempTable(
MyId BIGINT,
SomeOtherId BIGINT
)
uj5u.com熱心網友回復:
根據腳本,我可以看到,在第一個查詢中,您使用的是 Compare1.*,第二個是 Compare2.*。所以看起來兩個表都有不同的結構。所以我的建議是給出確切的列名并將其映射到實際目的地,而不僅僅是將 *.
這樣的事情應該有幫助
IF OBJECT_ID('Tempdb..#TMP;') IS NOT NULL
DROP TABLE #TMP;
select
Destination1 = A.Column1,
Destination2 = A.Column2,
Destination3 = 'table A'
INTO #TMP
from #compare1 a
full outer join #compare2 b
on a.hash = b.hash
where ( a.hash is null or b.hash is null );
INSERT INTO #TMP
(
Destination1,
Destination2,
Destination3
)
select
B.Column1,
B.Column2,
'table B'
from #compare1 a
full outer join #compare2 b
on a.hash = b.hash
where ( a.hash is null or b.hash is null );
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340088.html
標籤:sql sql-server
上一篇:如果作業表名稱中有空格(SSIS),如何跳過OpenRowset中xlsx源的前幾行?
下一篇:按列展開資料
