我有一个相当大的查询,我在特定的数据库上运行。这个查询所做的是从特定表中选择特定列并将它们转储到新表中。新表在查询中稍后使用和修改。“无效的列名称” - 查询失败
我遇到的问题是,虽然数据库应该是来自同一个程序,但一个数据库可能有列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]
email1,email2,email3 ....听起来像是一个非常糟糕的设计。这些应该是行,而不是列。 – fancyPants
我不会在那里不同意你的意见。我们从不同的软件获取数据库,有时他们访问数据库,有时是SQL Server,有时只是访问Excel电子表格,我们将数据移动到SQL数据库以供我们的软件使用。这个特定的数据库是一个SQL数据库,但它做得很差(例如,有一个名称字段,其中第一个,中间,最后一个和/或公司名称)。更糟糕的是,这个其他软件并没有限制你如何使用它的领域。你可以使用一堆数字来填写email3字段,而不使用email1。 –
恐怕我没有正确的解决问题。你可以发布示例查询吗? – fancyPants