2017-09-22 44 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); 
相關問題