2013-01-17 170 views
0

我有一個相當大的查詢,我在特定的數據庫上運行。這個查詢所做的是從特定表中選擇特定列並將它們轉儲到新表中。新表在查詢中稍後使用和修改。「無效的列名稱」 - 查詢失敗

我遇到的問題是,雖然數據庫應該是來自同一個程序,但一個數據庫可能有列email1,email2和email3,但下一個可能只有email1。由於email1-3用作select語句的一部分,因此當其中一個列缺失時,該部分將失敗,並且該表永遠不會創建。

我還是非常新的這個,所以我的問題可能是簡單或愚蠢的,但有沒有什麼辦法可以保存結果時,一列失蹤像這樣?我可以輕鬆地刪除查詢中缺少的列並重新運行它,但是我想知道是否有更正確的方法來執行此操作?

例子:

SELECT Customer.[Name], 
    Customer.AcctKey, 
    SUBSTRING(Customer.LastName,1,25) AS [Last Name], 
    SUBSTRING(Customer.FirstName,1,25) AS [First Name], 
    Customer.Add1 AS Address, 
    Customer.Add2 AS Address2, 
    Customer.City, 
    Customer.State,     
    Customer.Zip, 
    Location.Add1 AS [Ship Address], 
    Location.Add2 AS [Ship Address2], 
    Location.City AS [Ship City], 
    Location.State AS [Ship State], 
    Location.Zip AS [Ship Zip], 
    Customer.Phone1 AS Phone, 
    Customer.Phone2 AS [Alt Phone], 
    Customer.Phone3 AS [Cell Phone], 
    Customer.Phone4 AS Fax, 
    Customer.lblPhone1, 
    Customer.lblPhone2, 
    Customer.lblPhone3, 
    Customer.lblPhone4, 
    Customer.Terms, 
    Customer.[Key] AS [Account Number], 
    Location.Notes, 
    Location.TaxCode AS [Tax Item], 
    Location.Zone AS [Map Code], 
    Location.Contact, 
    Location.Email, 
    Location.Email6, --Fails because column(s) Email2-6 
    Location.Email5, --don't exist in this database 
    Location.Email4, --but they might in another 
    Location.Email3, --and I'd like to get the data 
    Location.Email2, --if they do 
    Location.Phone6, 
    Location.Phone5 

INTO [01Parents] 
FROM Customer 
INNER JOIN Location ON Customer.[Key] = Location.[Key] 
+1

email1,email2,email3 ....聽起來像是一個非常糟糕的設計。這些應該是行,而不是列。 – fancyPants

+0

我不會在那裏不同意你的意見。我們從不同的軟件獲取數據庫,有時他們訪問數據庫,有時是SQL Server,有時只是訪問Excel電子表格,我們將數據移動到SQL數據庫以供我們的軟件使用。這個特定的數據庫是一個SQL數據庫,但它做得很差(例如,有一個名稱字段,其中第一個,中間,最後一個和/或公司名稱)。更糟糕的是,這個其他軟件並沒有限制你如何使用它的領域。你可以使用一堆數字來填寫email3字段,而不使用email1。 –

+0

恐怕我沒有正確的解決問題。你可以發佈示例查詢嗎? – fancyPants

回答

0

你可以嘗試以下。

DECLARE @SQL AS NVARCHAR(MAX) 

SELECT 
    @SQL = COALESCE(@SQL, N'') + CASE WHEN @SQL IS NULL THEN c.name ELSE N', ' + c.name END 
FROM 
    sys.columns AS c INNER JOIN sys.objects AS o 
     ON 
      c.object_id = o.object_id 
WHERE 
    o.name = @table 
ORDER BY 
    c.column_id 

SET @SQL = N'SELECT ' + @SQL + N' INTO 01Parents FROM Customer INNER JOIN ON Customer.[Key] = Location.[Key]' 

EXEC sp_executesql @sql 
+0

只需檢查,看看這是否適合你。 (或者如果你嘗試過。) – JoeFletch