“无效的列名称” - 查询失败

时间:2013-01-17 14:25:08

标签: tsql select failover

我有一个相当大的查询,我在特定的数据库上运行。此查询的作用是从特定表中选择特定列并将它们转储到新表中。稍后将在查询中使用和修改新表。

我遇到的问题是,虽然数据库应该来自同一个程序,但是一个数据库可能包含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 个答案:

答案 0 :(得分: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