在子选择查询中对临时表进行别名的潜在问题

时间:2012-03-16 16:29:37

标签: sql stored-procedures aliasing

我希望这格式正确。我遇到了这个程序的问题。我已经删除了声明,你看到的是主体。我要做的就是创建一个表变量(在SQL SERVER 2000中)并从其中包含的数据中提取一些指标。

DECLARE @InvoiceData TABLE
(
UserID      INT
, FullName  VARCHAR
, StatusId  INT
, Status    VARCHAR
, DateCreated DATETIME
)

--INSERT INTO @InvoiceData(UserID, FullName, StatusId, Status, DateCreated)
SELECT
tblInvoiceInstructions.AccountantUserId
, Users.Name + ', ' + Users.First_Name AS FullName
, tblInvoice.CurrentWorkflowStatusId AS StatusID
, dbo.ufnGetGenericCodeLongDescText(tblInvoice.CurrentWorkflowStatusId,GETDATE()) AS Status
, CONVERT(VARCHAR, tblInvoice.DateCreated, 101) AS DateCreated
FROM tblInvoiceInstructions
JOIN tblInvoice ON tblInvoice.Project_ID = tblInvoiceInstructions.ProjectID
LEFT JOIN dbo.Users ON tblInvoiceInstructions.AccountantUserId = Users.UserId
WHERE tblInvoice.DateCreated BETWEEN @StartDate AND @EndDate


SELECT FullName, InvoicesAssigned, InvoicesApproved, InvoicesRejected, InvoicesAssigned-InvoicesApproved-InvoicesRejected AS InvoicesRemaining
FROM 
(
SELECT DISTINCT FullName
,ISNULL((SELECT COUNT(t2.StatusID) FROM @InvoiceData t2 WHERE t2.AccountantUserId = T1.AccountantUserId GROUP BY FullName),0) AS InvoicesAssigned
,ISNULL((SELECT COUNT(t2.StatusID) FROM @InvoiceData t2 WHERE t2.StatusID = 394 AND t2.AccountantUserId = T1.AccountantUserId GROUP BY FullName),0) AS InvoicesApproved
,ISNULL((SELECT COUNT(t2.StatusID) FROM @InvoiceData t2 WHERE t2.StatusID = 388 AND t2.AccountantUserId = T1.AccountantUserId GROUP BY FullName),0) AS InvoicesRejected
FROM @InvoiceData T1
) AS InnerTable

当我执行存储过程时,它会给我以下错误6次:

Msg 207,Level 16,State 3,Procedure uspReportInvoicesProcessedAndWaiting,Line 31 列名称“AccountantUserId”无效。

第31行是外部选择,我在其中为FullName,InvoicesAssigned,InvoicesApproved提取值。等等。我错误地将表格混淆了吗?

1 个答案:

答案 0 :(得分:0)

在第二个查询中检查此行。

ISNULL((SELECT COUNT(t2.StatusID) FROM @InvoiceData t2 
WHERE t2.AccountantUserId = T1.AccountantUserId GROUP BY FullName),0) 
AS InvoicesAssigned

注意: @InvoiceData别名t2未定义 AccountantUserId 列。 t2.AccountantUserId 不存在。

检查@InvoiceData表定义