我有一个SalesTransaction
和一个Invoice
表:
Create Table SalesTransaction
(
SalesTransactionId int Identity(1,1) Primary Key,
CustomerId int Foreign key references Customer(CustomerId) ,
ProductId int Foreign key references Product(ProductID),
Price money,
Quantity int,
Total money,
InvoiceId int
)
和
Create Table Invoice
(
InvoiceId int Primary Key,
InvoiceAmount money Not Null ,
BalanceAmount money,
AmountPaid money Not Null
)
我想要的是Invoiceid
从Invoice
表到InvoiceId
表格的SalesTransaction
。
首先InvoiceId
的{{1}}为NULL,并且在添加了发票表的数据之后,它应该标记回SalesTransaction
表的InvoiceId
答案 0 :(得分:1)
对于以下架构
Create Table Invoice
(
InvoiceId int Primary Key,
InvoiceAmount money Not Null ,
BalanceAmount money,
AmountPaid money Not Null
)
Create Table SalesTransaction
(
SalesTransactionId int Identity(1,1) Primary Key,
CustomerId int Foreign key references Customer(CustomerId) ,
ProductId int Foreign key references Product(ProductID),
Price money,
Quantity int,
Total money,
InvoiceId int Foreign key references Invoice(InvoiceId)
)
以下是您的INSERT / UPDATE查询
DECLARE @SalesTransactionId as int
DECLARE @InvoiceId as int
INSERT INTO [dbo].[SalesTransaction]
([CustomerId]
,[ProductId]
,[Price]
,[Quantity]
,[Total]
,[InvoiceId])
VALUES
(1
,1
,1
,1
,1
,NULL)
SET @SalesTransactionId = SCOPE_IDENTITY()
SET @InvoiceId = 1
INSERT INTO [dbo].[Invoice]
([InvoiceId]
,[InvoiceAmount]
,[BalanceAmount]
,[AmountPaid])
VALUES
(@InvoiceId
,1
,1
,1)
UPDATE [dbo].[SalesTransaction]
SET [InvoiceId] = @InvoiceId
WHERE SalesTransactionId = @SalesTransactionId
GO
我还建议您将表InvoiceId
的列Invoice
设置为标识。
对于以下架构
Create Table Invoice
(
InvoiceId int Identity(1,1) Primary Key,
InvoiceAmount money Not Null ,
BalanceAmount money,
AmountPaid money Not Null
)
Create Table SalesTransaction
(
SalesTransactionId int Identity(1,1) Primary Key,
CustomerId int Foreign key references Customer(CustomerId) ,
ProductId int Foreign key references Product(ProductID),
Price money,
Quantity int,
Total money,
InvoiceId int Foreign key references Invoice(InvoiceId)
)
以下是您的INSERT / UPDATE查询
DECLARE @SalesTransactionId as int
DECLARE @InvoiceId as int
INSERT INTO [dbo].[SalesTransaction]
([CustomerId]
,[ProductId]
,[Price]
,[Quantity]
,[Total]
,[InvoiceId])
VALUES
(1
,1
,1
,1
,1
,NULL)
SET @SalesTransactionId = SCOPE_IDENTITY()
INSERT INTO [dbo].[Invoice]
([InvoiceAmount]
,[BalanceAmount]
,[AmountPaid])
VALUES
(1
,1
,1)
SET @InvoiceId = SCOPE_IDENTITY()
UPDATE [dbo].[SalesTransaction]
SET [InvoiceId] = @InvoiceId
WHERE SalesTransactionId = @SalesTransactionId
GO