Insert and select in one statement [duplicate] - c#

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get last inserted id?
I have a table Absences
| Id | Name | Job |
-------------------------
| 1 |  James | 1 |
-------------------------
| 2 | Simon |  1 |
-------------------------
Where ID is an identity Primary Key incrementing by 1.
I'm accessing this table from a program in C# and I need to do the following :
Insert Into Absences (Name, Job) Values ('aName', 'aJob')
The problem is I need to get the Id column where i'm inserting at the same time because Nameand Job are not unique so I won't be able to retreive this exact column after.
Is it possible to add a select on the Id column in that query ?
Update
SqlConnection myConnection = new SqlConnection(#"SomeConnection");
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "Insert Into Absences (Name, Job) Values ('aName', 'aJob')";
int currentAbs = (int)myCommand.ExecuteScalar();
I get an error on the ExecuteScalar Line. Object reference is not set to and instance of object.

The SQL statement SCOPE_IDENTITY() will give you the value of the identity column of the newly inserted row from within the same scope.
SqlConnection myConnection = new SqlConnection(#"SomeConnection");
myConnection.Open();
SqlCommand myCommand = myConnection.CreateCommand();
myCommand.CommandText = "Insert Into Absences (Name, Job) Values ('aName', 'aJob'); SELECT SCOPE_IDENTITY();";
int currentAbs = (int)myCommand.ExecuteScalar();
Scope Identity Definition

If you use SqlCommand, then you can use
int lastId = (int)command.ExecuteScalar();
to retrieve the unique id of the inserted record.
Take a look at Microsoft page.

After this query you can select ##identity to get the last inserted id in mssql server.

One way would be to use SELECT ##IDENTITY immediately after you insert your record:
int id;
string query = "Insert Into Absences (Name, Job) Values ('aName', 'aJob')";
using (SqlCommand cmd = new SqlCommand(query, connection)) {
connection.Open();
// execute your INSERT query
cmd.ExecuteNonQuery();
// get the last-inserted ID
cmd.CommandText = "SELECT ##IDENTITY";
id = (int)cmd.ExecuteScalar();
}

Related

Get id from the last entry

I need to insert a product into a ProductDB table and at the same time get the id from the product I just inserted, so I can use it in the next query as a Foreign Key I have been looking at different methods like "select last_insert_rowid()" and "SCOPE_IDENTITY()" but I can't get it to work, how do I get it to work
public static void SaveProduct(ProductModel product)
{
using (IDbConnection cnn = new SQLiteConnection(LoadConnectionString()))
{
cnn.Execute("INSERT INTRO ProductDB (Name, Price) VALUES (#Name, #Price);",
product);
string ForeignKey = "the id from the last entry from the query above";
cnn.execute("INSERT INTO ImageDB (Filename, Path, FK_Product) VALUES (#Filename, #Path," + ForeignKey + " )");
}
}
In SQL Server has 3 functions (methods) for getting the last inserted id from the table.
IDENT_CURRENT() - returns the last-inserted identity value for a given table.
SCOPE_IDENTITY() - returns the last identity value inserted into an identity column in any table in the current session and current scope.
##IDENTITY - returns the last inserted identity value in any table in the current session, regardless of scope.
We need SCOPE_IDENTITY(), so ATTENTION!!!
This function must be used in the current scope, which located insert command.
Example:
declare
#new_id integer;
INSERT INTRO ProductDB (Name, Price) VALUES (#Name, #Price);
SET #new_id = SCOPE_IDENTITY();
If you would use System.Data.SQLite you could use the LastInsertRowId property.
Example:
using (SQLiteConnection conn = new SQLiteConnection(#"Data Source=.\Test.db"))
{
conn.Open();
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = $"INSERT INTO Test (name) values ('{Guid.NewGuid().ToString()}');";
cmd.ExecuteNonQuery();
id = conn.LastInsertRowId;
conn.Close();
}

how can i update SQL table logic

I have a table structured as,
Table 3
Fruit ID - Foreign Key (Primary Key of Table 1)
Crate ID - Foreign Key (Primary Key of Table 2)
Now I need to execute a query which will,
Update Crate ID of Fruit ID if Fruit ID is already in Table, and if not then insert record in table 3 as new record.
This is what I got in code right now,
private void RelateFuirtWithCrates(List<string> selectedFruitIDs, int selectedCrateID)
{
string insertStatement = "INSERT INTO Fruit_Crate(FruitID, CrateID) Values " +
"(#FruitID, #CrateID);"; ?? I don't think if it's right query
using (SqlConnection connection = new SqlConnection(ConnectionString()))
using (SqlCommand cmd = new SqlCommand(insertStatement, connection))
{
connection.Open();
cmd.Parameters.Add(new SqlParameter("#FruitID", ????? Not sure what goes in here));
cmd.Parameters.Add(new SqlParameter("#CrateID",selectedCrateID));
}
You can do an "upsert" with the MERGE syntax in SQL Server:
MERGE [SomeTable] AS target
USING (SELECT #FruitID, #CrateID) AS source (FruitID, CrateID)
ON (target.FruitID = source.FruitID)
WHEN MATCHED THEN
UPDATE SET CrateID = source.CrateID
WHEN NOT MATCHED THEN
INSERT (FruitID, CrateID)
VALUES (source.FruitID, source.CrateID);
Otherwise, you can use something like:
update [SomeTable] set CrateID = #CrateID where FruitID = #FruitID
if ##rowcount = 0
insert [SomeTable] (FruitID, CrateID) values (#FruitID, #CrateID)

How to get last id if any column in SQL Server 2005? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get last inserted id?
I am trying to get the last id (Last value of an identity column) to show it on control incremented by 1 each time when data is inserted to table.
How to get this last id in a stored procedure in SQL Server 2005 using C#?
Identity columns are incremented in the database, not on the C# side. You can query for the last value like this:
SELECT MAX(id) FROM mytable
Either just grab the latest ID when the insert happens (using SCOPE_IDENTITY()), or if you need to check the current value of an IDENTITY column later on, use SELECT IDENT_CURRENT('table_name') to get that value.
So the easiest way is to just get the ID as you insert your values - something like this:
string sql = "INSERT INTO dbo.YourTable(Col1, ..., ColN) VALUES(#Val1, ..., #ValN); SELECT SCOPE_IDENTITY()";
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
Or if you cannot grab the ID as it's being inserted, you can always check later on what the current last used value of the IDENTITY column on a given table was, using something like this:
string sql = string.Format("SELECT IDENT_CURRENT('{0}');", yourTableName);
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
conn.Close();
}
You can use this
SELECT ##IDENTITY AS 'Identity';
or this
SELECT MAX(SomeID) FROM SomeTable;
EDIT
Best way to use
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
and in C# you could call
Int32 _ID = 0;
//you could use second variant sql= "SELECT MAX(SomeID) FROM SomeTable";
string sql =
"SELECT ##IDENTITY AS 'Identity'";
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
try
{
conn.Open();
_ID = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
EDIT
Nice link to feel difference
Using ##IDENTITY and SCOPE_IDENTITY with triggers
SELECT TOP 1 Id FROM table_name ORDER BY 1 DESC
or in LINQ:
context.table.Select(x->x.Id).OrderByDescending(x->x.Id).FirstOrDefault();

How can i get the ##IDENTITY returned from a INSERT from MySQL (2008) using C# [duplicate]

Using C# in Visual Studio, I'm inserting a row into a table like this:
INSERT INTO foo (column_name)
VALUES ('bar')
I want to do something like this, but I don't know the correct syntax:
INSERT INTO foo (column_name)
VALUES ('bar')
RETURNING foo_id
This would return the foo_id column from the newly inserted row.
Furthermore, even if I find the correct syntax for this, I have another problem: I have SqlDataReader and SqlDataAdapter at my disposal. As far as I know, the former is for reading data, the second is for manipulating data. When inserting a row with a return statement, I am both manipulating and reading data, so I'm not sure what to use. Maybe there's something entirely different I should use for this?
SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.
using (var con = new SqlConnection(ConnectionString)) {
int newID;
var cmd = "INSERT INTO foo (column_name)VALUES (#Value);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, con)) {
insertCommand.Parameters.AddWithValue("#Value", "bar");
con.Open();
newID = (int)insertCommand.ExecuteScalar();
}
}
try this:
INSERT INTO foo (column_name)
OUTPUT INSERTED.column_name,column_name,...
VALUES ('bar')
OUTPUT can return a result set (among other things), see: OUTPUT Clause (Transact-SQL). Also, if you insert multiple values (INSERT SELECT) this method will return one row per inserted row, where other methods will only return info on the last row.
working example:
declare #YourTable table (YourID int identity(1,1), YourCol1 varchar(5))
INSERT INTO #YourTable (YourCol1)
OUTPUT INSERTED.YourID
VALUES ('Bar')
OUTPUT:
YourID
-----------
1
(1 row(s) affected)
I think you can use ##IDENTITY for this, but I think there's some special rules/restrictions around it?
using (var con = new SqlConnection("connection string"))
{
con.Open();
string query = "INSERT INTO table (column) VALUES (#value)";
var command = new SqlCommand(query, con);
command.Parameters.Add("#value", value);
command.ExecuteNonQuery();
command.Parameters.Clear();
command.CommandText = "SELECT ##IDENTITY";
int identity = Convert.ToInt32(command.ExecuteScalar());
}

Return value from SQL Server Insert command using c#

Using C# in Visual Studio, I'm inserting a row into a table like this:
INSERT INTO foo (column_name)
VALUES ('bar')
I want to do something like this, but I don't know the correct syntax:
INSERT INTO foo (column_name)
VALUES ('bar')
RETURNING foo_id
This would return the foo_id column from the newly inserted row.
Furthermore, even if I find the correct syntax for this, I have another problem: I have SqlDataReader and SqlDataAdapter at my disposal. As far as I know, the former is for reading data, the second is for manipulating data. When inserting a row with a return statement, I am both manipulating and reading data, so I'm not sure what to use. Maybe there's something entirely different I should use for this?
SCOPE_IDENTITY returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch.
You can use SqlCommand.ExecuteScalar to execute the insert command and retrieve the new ID in one query.
using (var con = new SqlConnection(ConnectionString)) {
int newID;
var cmd = "INSERT INTO foo (column_name)VALUES (#Value);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, con)) {
insertCommand.Parameters.AddWithValue("#Value", "bar");
con.Open();
newID = (int)insertCommand.ExecuteScalar();
}
}
try this:
INSERT INTO foo (column_name)
OUTPUT INSERTED.column_name,column_name,...
VALUES ('bar')
OUTPUT can return a result set (among other things), see: OUTPUT Clause (Transact-SQL). Also, if you insert multiple values (INSERT SELECT) this method will return one row per inserted row, where other methods will only return info on the last row.
working example:
declare #YourTable table (YourID int identity(1,1), YourCol1 varchar(5))
INSERT INTO #YourTable (YourCol1)
OUTPUT INSERTED.YourID
VALUES ('Bar')
OUTPUT:
YourID
-----------
1
(1 row(s) affected)
I think you can use ##IDENTITY for this, but I think there's some special rules/restrictions around it?
using (var con = new SqlConnection("connection string"))
{
con.Open();
string query = "INSERT INTO table (column) VALUES (#value)";
var command = new SqlCommand(query, con);
command.Parameters.Add("#value", value);
command.ExecuteNonQuery();
command.Parameters.Clear();
command.CommandText = "SELECT ##IDENTITY";
int identity = Convert.ToInt32(command.ExecuteScalar());
}

Categories