by by子句中的模糊列名称错误

时间:2012-10-17 04:06:28

标签: sql sql-server sql-server-2008

为什么这个查询不起作用?

SELECT ROW_NUMBER() OVER (
        ORDER BY DocumentID
        ) peta_rn
    , d.DocumentID
    , d.IsReEfiled
    , d.IGroupID
    , d.ITypeID
    , d.RecordingDateTime
    , dbo.GetLatestStatusDateTime(d.DocumentID) AS LatestStatusDatetime
    , dbo.FnCanChangeDocumentStatus(d.DocumentStatusID, d.DocumentID) AS CanChangeStatus
    , d.IDate
    , d.InstrumentID
    , d.DocumentStatusID
    , ig.Abbreviation AS IGroupAbbreviation
    , u.Username
    , j.JDAbbreviation
    , inf.DocumentName
    , it.Abbreviation AS ITypeAbbreviation
    , d.DocumentDate
    , ds.Abbreviation AS DocumentStatusAbbreviation
    , dbo.GetFlatDocumentName(d.DocumentID) AS FlatDocumentName
FROM Documents d
INNER JOIN IGroupes ig
    ON d.IGroupID = ig.IGroupID
LEFT JOIN ITypes it
    ON d.ITypeID = it.ITypeID
LEFT JOIN Users u
    ON u.UserID = d.UserID
LEFT JOIN DocumentStatuses ds
    ON d.DocumentStatusID = ds.DocumentStatusID
LEFT JOIN InstrumentFiles inf
    ON d.DocumentID = inf.DocumentID
INNER JOIN Jurisdictions j
    ON j.JurisdictionID = d.JurisdictionID
WHERE 1 = 1

而这个有效:

SELECT ROW_NUMBER() OVER (
        ORDER BY d.DocumentID
        ) peta_rn
    , d.DocumentID
    , d.IsReEfiled
    , d.IGroupID
    , d.ITypeID
    , d.RecordingDateTime
    , dbo.GetLatestStatusDateTime(d.DocumentID) AS LatestStatusDatetime
    , dbo.FnCanChangeDocumentStatus(d.DocumentStatusID, d.DocumentID) AS CanChangeStatus
    , d.IDate
    , d.InstrumentID
    , d.DocumentStatusID
    , ig.Abbreviation AS IGroupAbbreviation
    , u.Username
    , j.JDAbbreviation
    , inf.DocumentName
    , it.Abbreviation AS ITypeAbbreviation
    , d.DocumentDate
    , ds.Abbreviation AS DocumentStatusAbbreviation
    , dbo.GetFlatDocumentName(d.DocumentID) AS FlatDocumentName
FROM Documents d
INNER JOIN IGroupes ig
    ON d.IGroupID = ig.IGroupID
LEFT JOIN ITypes it
    ON d.ITypeID = it.ITypeID
LEFT JOIN Users u
    ON u.UserID = d.UserID
LEFT JOIN DocumentStatuses ds
    ON d.DocumentStatusID = ds.DocumentStatusID
LEFT JOIN InstrumentFiles inf
    ON d.DocumentID = inf.DocumentID
INNER JOIN Jurisdictions j
    ON j.JurisdictionID = d.JurisdictionID
WHERE 1 = 1

正如您所看到的,唯一的区别是我指定了d.DocumentID。无论如何,我可以避免指定d.DocumentID而只指定DocumentID而不使用额外的选择?毕竟,所有documentID都引用相同的值。

2 个答案:

答案 0 :(得分:4)

问题是DocumentID位于InstrumentFilesDocuments两个表中,那么查询引擎如何知道您指的是哪一个?

简而言之,,您必须在此实例中指定d.DocumentID

答案 1 :(得分:2)

没有

您应该提供别名d,因为多个表包含DocumentID。引擎对应该采取的订单(或哪个表)感到困惑。