子查询返回多个值

时间:2013-09-10 08:17:32

标签: sql sql-server cursor subquery

SELECT [Acc_DocumentNo],[Acc_DocumentDate],[Acc_DocumentType],[Acc_DocumentRef],[Acc_DocumentAmount],
    [Acc_CustomerID],[Acc_DebtorGroupID],[Acc_DebtorBranchID],
    (SELECT Acc_ManualReferenceNo
        FROM Acc_CreditDocuments
        WHERE Acc_DocumentNo IN 
        (SELECT Acc_DocumentRef FROM Acc_CreditDocuments 
    WHERE Acc_DocumentNo = @DocumentNo)) As [Acc_ManualReferenceNo],
        [Acc_Status],[Acc_CreatedBy],[Acc_CreatedAt],[Acc_ModifiedBy],[Acc_ModifiedAt]
FROM Acc_CreditDocuments
WHERE Acc_DocumentNo = @DocumentNo AND
Acc_DocumentRef <> Acc_DocumentNo

在上面的查询中,如果选择Acc_ManualReferenceNo的子查询语句有多个DocumentNo,则返回多个值。

我可以打开db cursor来获取并逐个插入值吗?或者还有其他方法吗?

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

JOIN表格本身就是这样的:

SELECT 
  a1.[Acc_DocumentNo],
  a1.[Acc_DocumentDate],
  a1.[Acc_DocumentType],
  a1.[Acc_DocumentRef],
  a1.[Acc_DocumentAmount],
  a1.[Acc_CustomerID],
  a1.[Acc_DebtorGroupID],
  a1.[Acc_DebtorBranchID],
  a2.Acc_ManualReferenceNo As [Acc_ManualReferenceNo] -- < --
  ...
FROM Acc_CreditDocuments AS a1
INNER JOIN Acc_CreditDocuments AS a2 ON a1.cc_DocumentRef = a2.Acc_DocumentNo
WHERE Acc_DocumentNo = @DocumentNo 
  AND a1.Acc_DocumentRef <> a1.Acc_DocumentNo