Click here to Skip to main content
15,884,099 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a database and i am using c# to build wpf app
the database has 6 table and every one of them have a id,
so in my application, i have insert button, when i click it
the data goes to database but the id of other in the table i execute is
null so i want to use sql connection when i insert all the data
i also insert the id of other table in my table.

What I have tried:

i tried to select the id of the table to my table but it did not work
Posted
Updated 17-Mar-23 19:45pm
Comments
PIEBALDconsult 17-Mar-23 19:26pm    
You should know the IDs before you write the data.

1 solution

I'm going to assume that you are using IDENTITY columns for your ID's so that SQL generates them for you - if not then you are using UNIQUEIDENTIFIER / Guid ID (in which case you could generate them when you do the INSERT and then you wouldn't need to ask this question).

So you need to fetch the value of the IDENTITY column that was just INSERTED - and SQL lets you do that with the @@IDENTITY value or SCOPE_IDENTITY function[^] value - you can retrieve that into your C# code by adding a SELECT command to your INSERT and replacing the call to ExecuteNonQuery with ExecuteScalar.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900