如何加入四张桌子发票?

时间:2015-05-19 07:19:45

标签: tsql stored-procedures join invoice

我必须发出一张销售发票,创建了四个表:(在stimulsoft中发送变量)

如何使用此过程将这些表连接在一起?

这些是表格:

enter image description here

这是程序:



USE [RahgoshafanDB]
GO
/****** Object:  StoredProcedure [dbo].[Invoice_Soft] Script Date: 05/19/2015 10:30:26 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE Procedure [dbo].[Invoice_Soft]
@Invoice_Id int

AS
BEGIN
select
       dbo.Customer.Customer as customer,
       dbo.Customer.Tel as tel,
       dbo.Customer.Adr as adr,
       dbo.Software_Invoice.Dat as dat,
       dbo.Software_Invoice.Payable as payable,
       dbo.Software_Invoice.Discount as discount,
       dbo.Software.Software as software,
       dbo.Software_Order.Price as price,
       dbo.Software_Order.Quantity as quantity,
       dbo.Software_Order.Sum as sum
       From dbo.Software_Invoice inner join dbo.Customer 
       on dbo.Software_Invoice.Customer_Id = dbo.Customer.Id  AND     
       dbo.Software_Invoice.Id = dbo.Software_Order.Invoice_Id   
       where  dbo.Software_Invoice.Id = @Invoice_Id
END




但它不起作用!

2 个答案:

答案 0 :(得分:2)

您缺少两个JOIN - 陈述:

FROM dbo.Software_Invoice
    INNER JOIN dbo.Customer 
        ON dbo.Software_Invoice.Customer_Id = dbo.Customer.Id
    INNER JOIN dbo.Software_Order     
        ON dbo.Software_Invoice.Id = dbo.Software_Order.Invoice_Id 
    INNER JOIN dbo.Software
        ON dbo.Software_Order.Software_Id = dbo.Software.Id

这应该可以解决它。

<强>解释

使用SQL JOIN时,您将使用新表加入现有的内容。因此,加入两个表格,您将使用

SELECT *
FROM [Table1]
INNER JOIN [Table2]
    ON [Table1].[ForeignKeyToTable2] = [Table2].[PrimaryKey]

ON部分可以是任何条件,不一定是外键关系。

加入这两个表之后,你现在有一个新的&#34;表&#34;由两个表的所有列组成([Table1].*[Table2].*)。然后可以使用新的JOIN语句进一步加入:

INNER JOIN [Table3]
    ON [Table3].[Column] = [Table1/2].[Column]

ON语句还可以包含几个条件,例如:

ON [Table3].[Column1] = [Table1].[Column1]
    AND [Table3].[Column2] = [Table2].[Column1]

答案 1 :(得分:1)

您错过了INNER JOIN 请添加

INNER JOIN dbo.Software_Order ON dbo.Software_Invoice.Id = dbo.Software_Order.Invoice_Id
祝你好运。