2017-09-22 45 views
0

我正在使用存储过程来插入数据。 我有2个表格来存储客户的详细信息,另一个用于存储付款历史记录。所以当我按下我的窗体上的插入细节按钮时,这个存储过程被调用。我必须同时在两个表中插入数据。如何在sqlClient中插入数据的同时获取自动递增的id?

[DBO]。[为CustomerDetails]具有主键客户ID被设定为自动递增

因此,在插入的时候,我想这客户编号设置为[DBO]的recordId [PaymentHistory] ​​

注意:所有其他信息可以是相同的,但每个帐户是有区别的在为CustomerDetails主键客户ID

INSERT INTO [dbo].[CustomerDetails] ([CustomerName], [FatherName], [Cnic], [ContactNo], [Address], [City], [StartDate], [EndDate],[SamanDesc], [Tola], [Masha], [Rati], [Location], [Amount], [Percentage], [Months], [Days], [Status]) 
VALUES (@CustomerName, @FatherName, @Cnic, @ContactNo, @Address, @City, @StartDate, @EndDate, @SamanDesc, @Tola, @Masha, @Rati, @Location, @Amount, @Percentage, @Months, @Days, @Status); 

INSERT INTO [dbo].[PaymentHistory] ([RecordId], [DatePaid], [Amount], [AmountPaid], [Profit]) 
VALUES (@id, @StartDate, @Amount, 0, 0); 
+0

一种解决方法是做一个选择查询正确插入[为CustomerDetails后]并从表格中获取最新插入的ID。 – MasoodUrRehman

+0

请问如何获取最新的ID的方法? – Ezaz

+0

使用['OUTPUT'子句](https://docs.microsoft.com/zh-cn/sql/t-sql/queries/output-clause-transact-sql)。 – Oliver

回答

0

如果你的数据库是MySQL的,使用

select last_insert_id() from dual;

这将检索此信息。

+0

我正在使用SqlClient – Ezaz

+0

好吧,我不知道sqlclient,但由于其名称,我怀疑这个软件允许tyou连接到数据库。我的问题是,你连接到哪个数据库? –

+0

那么它更可能用于处理桌面应用程序的数据库。 – Ezaz

1

嗨,大家好我使用SCOPE_IDENTITY解决我的问题。对于大多数应用程序,我们需要返回可以使用@@ IDENTITY,SCOPE_IDENTITY(),IDENT_CURRENT()的最新ID。那些不知道谁是什么,他们可以去这个链接,了解这些

https://www.codeproject.com/Articles/103610/Difference-between-IDENTITY-SCOPE-IDENTITY-IDENT-C

代码去如下:

DECLARE @id int; 

INSERT INTO [dbo].[CustomerDetails] ([CustomerName], [FatherName], [Cnic], [ContactNo], [Address], [City], [StartDate], [EndDate],[SamanDesc], [Tola], [Masha], [Rati], [Location], [Amount], [Percentage], [Months], [Days], [Status]) 
VALUES (@CustomerName, @FatherName, @Cnic, @ContactNo, @Address, @City, @StartDate, @EndDate, @SamanDesc, @Tola, @Masha, @Rati, @Location, @Amount, @Percentage, @Months, @Days, @Status); 

SET @id = (SELECT SCOPE_IDENTITY()); 

INSERT INTO [dbo].[PaymentHistory] ([RecordId], [DatePaid], [Amount], [AmountPaid], [Profit]) 
VALUES (@id, @StartDate, @Amount, 0, 0); 
相关问题