Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

enter data in 2 table at the same time

Posted on 2011-09-08
2
Medium Priority
?
237 Views
Last Modified: 2012-05-12
I want to enter data in two table at the same time and I am writing stored procedure for that.

Like you can consider customer table
PrimaryKey,FirstName,LastName,Age,Gender

For Payment table
Primarykey,UerID(Primarykey of customer tbale),Credictcardnumber,CVVcode,Expirationdate

I want to first enter data in custoemr table at the same time primarykey of custoemr tbale I want to enter in payment tbale.
I want to write stored procedure but I really don't know how can I enter custoemr table primary key into payment table at the same time.

Please help me out.I am not that much good in SQL
0
Comment
Question by:Itgirl16
2 Comments
 
LVL 6

Expert Comment

by:billfusion
ID: 36505825
One way you can do it is to create the customer ID and not rely the auto ID to get it for you, then use that ID to enter in both tables
0
 
LVL 14

Accepted Solution

by:
binaryevo earned 2000 total points
ID: 36505848
So write your insert into Customers query first and from that you do Select SCOPE_IDENTITY and that will return you the ID / PK field from your Customers table, from there you use that value in your second insert.


			INSERT INTO Customers(Col1,
									Col2,
									Col3)
			VALUES(@Col1,
				   @Col2,
				   @Col3)

			Declare @ScopeID int
			Set @ScopeID = (Select SCOPE_IDENTITY())
			
			INSERT INTO Table2(CustomerID,
							 Age)
			
			VALUES(@ScopeID,
				   @Age)	

Open in new window

0

Featured Post

Fill in the form and get your FREE NFR key NOW!

Veeam is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In real business world data are crucial and sometimes data are shared among different information systems. Hence, an agreeable file transfer protocol need to be established.
When trying to connect from SSMS v17.x to a SQL Server Integration Services 2016 instance or previous version, you get the error “Connecting to the Integration Services service on the computer failed with the following error: 'The specified service …
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question