关于“不明确的列名”的错误

时间:2017-02-05 19:50:05

标签: sql sql-server-2016

我在SQL Server 2016中只有一个查询示例:编写SQL代码,它将显示表InvoiceNumber中包含值的值INVOICE ............ ..

我需要加入3个表格。这是我的代码:

SELECT 
    InvoiceNumber
FROM 
    INVOICE AS I 
INNER JOIN 
    LINE_ITEM AS LI ON (I.InvoiceNumber = LI.InvoiceNumber)
INNER JOIN 
    PRODUCT AS P ON (LI.ProductNumber = P.ProductNumber)
WHERE 
    Description = 'Heather Sweeney Seminar Live in Dakkas on 25-OCT-09 - Video'

并且此代码总是会导致错误:

  

不明确的列名InvoiceNumber

WHERE查询

中的SELECT子句

2 个答案:

答案 0 :(得分:2)

始终限定查询中的所有列名称,尤其是当它具有多个表时:

SELECT I.InvoiceNumber
FROM INVOICE AS I INNER JOIN
     LINE_ITEM AS LI
     ON I.InvoiceNumber = LI.InvoiceNumber INNER JOIN
     PRODUCT P
     ON LI.ProductNumber = P.ProductNumber
WHERE P.Description = 'Heather Sweeney Seminar Live in Dakkas on 25-OCT-09 - Video'

如果你养成这种习惯,你就不会有这样的错误。

答案 1 :(得分:1)

如果2个表具有相同的列,则必须在查询中告诉您要使用哪个列。通过在它前面添加表名来做到这一点。

SELECT I.InvoiceNumber FROM INVOICE AS I ...