2016-12-22 71 views
0

我想把我的SQL Server表格拉到Excel工作表中。當我使用以下VBA代碼時,當前狀態不會篩選出「綁定」帳戶。SQL Server表格到Excel工作表

但是,當我嘗試不刪除像下面的第二個VBA代碼片段的表,然後它的工作。由於執行速度更快,我正在使用「Drop」。我不確定我是否在下面的第一個代碼中錯誤地在VBA中聲明瞭我的Drop表。任何建議/更正將不勝感激。

objMyCmd.CommandText = " IF OBJECT_ID('tempdb..#Step1') IS NOT NULL DROP TABLE #Step1 " & _ 
         " SELECT a.[RDT_FileID],a.[Master Policy Number], a.[Work item /Submission no#],a.[Insured Name], a.[Credited Office], " & _ 
           " a.[Credited Underwriter], a.[Product Line], a.[Product Line Subtype], a.[Current Status], a.[Effective Date], a.[Expiry Date], a.[Premium in USD $] " & _ 
           " FROM dbo.View_Property_Rater_Of_Record a " & _ 
           " WHERE a.[Master Policy Number] Is Not Null " & _ 
           " AND a.[RDT_FileID] is null " & _ 
           " AND a.[Product Line Subtype] <> '0102-Marine' " & _ 
           " AND a.[Effective Date] >= '2014-04-01' " & _ 
           " SELECT * from #Step1 WHERE [Current Status] ='Bound' " 

以下是我的第二個代碼,我沒有刪除表,但進程速度顯着下降。任何想法在我的第一個代碼片段有什麼問題?

objMyCmd.CommandText = " SELECT a.[RDT_FileID],a.[Master Policy Number], a.[Work item /Submission no#],a.[Insured Name], a.[Credited Office], " & _ 
           " a.[Credited Underwriter], a.[Product Line], a.[Product Line Subtype], a.[Current Status], a.[Effective Date], a.[Expiry Date], a.[Premium in USD $] " & _ 
           " FROM dbo.View_Property_Rater_Of_Record a " & _ 
           " WHERE a.[Master Policy Number] Is Not Null " & _ 
           " AND a.[RDT_FileID] is null " & _ 
           " AND a.[Product Line Subtype] <> '0102-Marine' " & _ 
           " AND a.[Effective Date] >= '2014-04-01' " & _ 
           " AND a.[Current Status] ='Bound' " 
+2

你可能要考慮在SQL Server寫這作爲一個存儲過程,只是把它從你的VBA,而不是試圖硬編碼一組動態SQL命令。 – techturtle

+0

你正在使用哪些DBMS? –

+0

用vba寫這整個sql語句會影響性能嗎?我調用的表是一個視圖,我不希望它是存儲過程。 – Shasti

回答

0

如果您打算使用#temp表格堅持選項1,請嘗試此操作。我假設你正在使用MS SQL。我在表格中添加了一個BeginEnd。其次,我沒有看到你在哪裏將結果集到臨時表之前,所以添加INTO #Step1您FROM聲明:

objMyCmd.CommandText = "IF (Select object_id('TempDB..#Step1')) IS NOT NULL" & _ 
" Begin " & _ 
" Drop Table #Step1 " & _ 
" End " & _ 
" SELECT a.[RDT_FileID],a.[Master Policy Number], a.[Work item /Submission no#],a.[Insured Name], a.[Credited Office], " & _ 
           " a.[Credited Underwriter], a.[Product Line], a.[Product Line Subtype], a.[Current Status], a.[Effective Date], a.[Expiry Date], a.[Premium in USD $] " & _ 
           " INTO #Step1 " &_ 
           " FROM dbo.View_Property_Rater_Of_Record a " & _ 
           " WHERE a.[Master Policy Number] Is Not Null " & _ 
           " AND a.[RDT_FileID] is null " & _ 
           " AND a.[Product Line Subtype] <> '0102-Marine' " & _ 
           " AND a.[Effective Date] >= '2014-04-01' " & _ 
           " SELECT * from #Step1 WHERE [Current Status] ='Bound' " 
相關問題