Can you use a WHERE statement within an INSERT INTO statement in SQL?
here is what i am currently trying to do.
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
VALUES (#ComponentType, #CompDescr)
WHERE (AssetTagNumber = #TagNo)
But the compiler is having an issue with the WHERE statement.
thanks
***UPDATE****
This is the full code that i am using so far with amendments
protected void AddBut_Click(object sender, EventArgs e)
{
//still passing the Asset tag number forward here
var ID = Request.QueryString["Id"];
string sql = "";
using (SqlConnection con = new SqlConnection("Data Source: *******************)
{
sql = "IF (AssetTagNumber = #TagNo) " +
"BEGIN " +
"INSERT INTO AssetComponents(ComponentID, ComponentDescription) " +
"VALUES (#ComponentType, #CompDescr) " +
"END ";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
// try
// {
cmd.Parameters.AddWithValue("#TagNo", ID);
cmd.Parameters.AddWithValue("#ComponentType", TypeDDL.Text.Trim());
cmd.Parameters.AddWithValue("#CompDescr", DescrTB.Text.Trim());
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("ComponentDetails.aspx");
// }
// catch (SqlException ex) { MessageBox.Show(" "); }
// catch (Exception ex) { MessageBox.Show(" "); }
}
}
}
Im sorry i was not clear enough first time around.
What i want to do is insert a new record with a clause that says if this record has an existing PK then use this key to insert another entry for that record
Apologies once again
Why don't you just use IF-clause?
IF (AssetTagNumber = #TagNo)
BEGIN
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
VALUES (#ComponentType, #CompDescr)
END
For statements with WHERE script should look similar to:
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
SELECT #ComponentType, #CompDescr
FROM <table>
WHERE (AssetTagNumber = #TagNo)
You can not "conditionally insert" like that. The WHERE clause is only available for SELECT, UPDATE or DELETE.
To check whether you need to INSERT a new record, you need to use IF, as in:
IF NOT EXISTS (SELECT ...)
INSERT INTO ...
if EXISTS (select * from AssetComponents where AssetTagNumber = #TagNo)
Begin
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
(#ComponentType, #CompDescr)
End
Use this:
UPDATE AssetComponents
Set ComponentID=#ComponentType, ComponentDescription=#CompDesc
Where AssetTagNumber = #TagNo
WHERE clause is something that helps to filter record, so it preferably uses with either SELECT or UPDATE. For INSERT we normally use IF NOT EXISTS clause.
See Examples:
http://social.msdn.microsoft.com/Forums/sqlserver/en-US/724ab6f3-413f-4c59-9b68-776f3ecfa899/insert-if-not-exists-into
http://msdn.microsoft.com/en-us/library/ms174335.aspx
Also, after looking at documentation, we can see that INSERT statement has NO support for WHERE clause.
If records already exists you can perform eith UPDATE or DELETE with INSERT operations.
You can try like:
IF NOT EXISTS (SELECT * FROM AssetComponents WHERE (AssetTagNumber = #TagNo))
INSERT INTO AssetComponents(ComponentID, ComponentDescription) VALUES (#ComponentType, #CompDescr)
ELSE
--UPDATE fields
Consider INSERT SELECT:
INSERT INTO AssetComponents(ComponentID, ComponentDescription)
SELECT [fill out here] AS ComponentID,
[fill out here] AS ComponentDescription
FROM somesource
WHERE [condition]
This is a specialty of MS SQL Server so will not work in other databases. It sort of requires that your data are already in another table or other source that you can query.
Related
insert into customer (Advance,status)
values(#Advance,#status)
where Name='" + txtcname.Text.Trim() + "'";
in the above insert statement in going to insert 2 values based in condition but i'm getting error in where condition...
incorrect syntax near keyword where
this is the error
Insert query do not needs Where clause. Just write
insert into customer (Advance, status) values(#Advance, #status)
Are you trying to insert or update? if you need to update an existing record then use update instead of insert like this:
update customer set Advance=#Advance, status=#status
where Name='" + txtcname.Text.Trim() + "'";
EDIT
Aforementioned update query will serve the purpose but its recommended to use stored procedures/parameterized queries for SQL injection safety. You should following use approach:
Private void UpdateRecord(string advance,string status, string name)
{
//SqlConnection con
SqlCommand cmdUpdate = new SqlCommand("update customer set Advance = #Advance, status = #Status where Name=#Name", con);
cmdUpdate.Parameters.AddWithValue("#Advance", advance);
cmdUpdate.Parameters.AddWithValue("#Status", status);
cmdUpdate.Parameters.AddWithValue("#name", name);
cmdUpdate.ExecuteNonQuery();
}
Pass your data as following:
UpdateRecord(#Advance,#Status,txtcname.Text.Trim());
You can't use 'where' in an insert-statement.
To achieve the same result, you can insert all entries and delete the wrong.
You can use a select-statement after an insert, where you select entries from a table into another. This could be a solution for you, too.
Insert into customer (advance, status) values (...)
select advance, status
from anotherCustomerTable
where ...
P.S. try to prepare the where-part, too.
You can not add where clause with values. You can achieve this with following way
if you really want to insert new rows else you can follow the #Munawar solution
insert into customer (Advance, status)
SELECT #Advance,#status
FROM customer where Name='" + txtcname.Text.Trim() + "'"
I am trying to carry out an 'insert if not exists' statement, i am not receiving any errors and the row does not exist in the db, however it still will not add it. Executing a normal 'insert' works but not when the 'if not exists' is added.
I have also tried including BEGIN & END and it doesnt work.
Where am i going wrong??
string getStudentModuleId = "SELECT ModuleId FROM StudentModuleMarks WHERE Mark < 40";
SqlCommand myCommand = new SqlCommand(getStudentModuleId, MyConnection3);
try
{
moduleid = (int)myCommand.ExecuteScalar();
string addRepeat = "IF NOT EXISTS (SELECT * FROM StudentModules WHERE ModuleId = #moduleid AND SchoolYear = '2018') INSERT INTO StudentModules(StudentDegreeId, ModuleId, Repeat, SchoolYear, EnrolledStatus) VALUES (1,#moduleid,1,'2018','Active')";
SqlCommand command = new SqlCommand(addRepeat, MyConnection3);
command.Parameters.AddWithValue("#moduleid", moduleid);
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
It seems you are using sql server, For MySQL, you can follow this technique to insert record if it doesn't exist :
INSERT INTO StudentModules(StudentDegreeId, ModuleId, Repeat, SchoolYear, EnrolledStatus)
select 1,#moduleid, 1, '2018', 'Active' from dual
where NOT EXISTS (SELECT * FROM StudentModules WHERE ModuleId = #moduleid AND SchoolYear = '2018')
Please note that, in MySQL, you don't really need to have a table called dual to exist: it is a special table-name that can be used to select anything from it. And it will output a single record always with a SELECT query like above.
I have this code:
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(#UserId, #GameId)";
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("#UserId", newUserId);
myCommand.Parameters.AddWithValue("#GameId", newGameId);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
When I insert into this table, I have an auto_increment int primary key column called GamesProfileId, how can i get the last inserted one after this so I can use that id to insert into another table?
For SQL Server 2005+, if there is no insert trigger, then change the insert statement (all one line, split for clarity here) to this
INSERT INTO aspnet_GameProfiles(UserId,GameId)
OUTPUT INSERTED.ID
VALUES(#UserId, #GameId)
For SQL Server 2000, or if there is an insert trigger:
INSERT INTO aspnet_GameProfiles(UserId,GameId)
VALUES(#UserId, #GameId);
SELECT SCOPE_IDENTITY()
And then
Int32 newId = (Int32) myCommand.ExecuteScalar();
You can create a SqlCommand with CommandText equal to
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(#UserId, #GameId)
and execute int id = (int)command.ExecuteScalar.
This MSDN article will give you some additional techniques.
string insertSql =
"INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(#UserId, #GameId)SELECT SCOPE_IDENTITY()";
int primaryKey;
using (SqlConnection myConnection = new SqlConnection(myConnectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(insertSql, myConnection);
myCommand.Parameters.AddWithValue("#UserId", newUserId);
myCommand.Parameters.AddWithValue("#GameId", newGameId);
primaryKey = Convert.ToInt32(myCommand.ExecuteScalar());
myConnection.Close();
}
This will work.
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
#comp_name varchar(55) = 'Big Company',
#comp_regno nchar(8) = '12345678',
#comp_email nvarchar(50) = 'no1#home.com',
#recID INT OUTPUT
-- The '#recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE #tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '#recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO #tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (#comp_name, #comp_regno, #comp_email)
SET #recID = (SELECT tempID FROM #tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '#recID'. '#recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (#recID)
End
-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.
I was looking for something like this for ages, with this detailed break down, I hope this helps.
In pure SQL the main statement kools like:
INSERT INTO [simbs] ([En]) OUTPUT INSERTED.[ID] VALUES ('en')
Square brackets defines the table simbs and then the columns En and ID, round brackets defines the enumeration of columns to be initiated and then the values for the columns, in my case one column and one value. The apostrophes enclose a string
I will explain you my approach:
It might be not easy to understand but i hope useful to get the big picture around using the last inserted id. Of course there are alternative easier approaches. But I have reasons to keep mine. Associated functions are not included, just their names and parameter names.
I use this method for medical artificial intelligence
The method check if the wanted string exist in the central table (1). If the wanted string is not in the central table "simbs", or if duplicates are allowed, the wanted string is added to the central table "simbs" (2). The last inseerted id is used to create associated table (3).
public List<int[]> CreateSymbolByName(string SymbolName, bool AcceptDuplicates)
{
if (! AcceptDuplicates) // check if "AcceptDuplicates" flag is set
{
List<int[]> ExistentSymbols = GetSymbolsByName(SymbolName, 0, 10); // create a list of int arrays with existent records
if (ExistentSymbols.Count > 0) return ExistentSymbols; //(1) return existent records because creation of duplicates is not allowed
}
List<int[]> ResultedSymbols = new List<int[]>(); // prepare a empty list
int[] symbolPosition = { 0, 0, 0, 0 }; // prepare a neutral position for the new symbol
try // If SQL will fail, the code will continue with catch statement
{
//DEFAULT und NULL sind nicht als explizite Identitätswerte zulässig
string commandString = "INSERT INTO [simbs] ([En]) OUTPUT INSERTED.ID VALUES ('" + SymbolName + "') "; // Insert in table "simbs" on column "En" the value stored by variable "SymbolName"
SqlCommand mySqlCommand = new SqlCommand(commandString, SqlServerConnection); // initialize the query environment
SqlDataReader myReader = mySqlCommand.ExecuteReader(); // last inserted ID is recieved as any resultset on the first column of the first row
int LastInsertedId = 0; // this value will be changed if insertion suceede
while (myReader.Read()) // read from resultset
{
if (myReader.GetInt32(0) > -1)
{
int[] symbolID = new int[] { 0, 0, 0, 0 };
LastInsertedId = myReader.GetInt32(0); // (2) GET LAST INSERTED ID
symbolID[0] = LastInsertedId ; // Use of last inserted id
if (symbolID[0] != 0 || symbolID[1] != 0) // if last inserted id succeded
{
ResultedSymbols.Add(symbolID);
}
}
}
myReader.Close();
if (SqlTrace) SQLView.Log(mySqlCommand.CommandText); // Log the text of the command
if (LastInsertedId > 0) // if insertion of the new row in the table was successful
{
string commandString2 = "UPDATE [simbs] SET [IR] = [ID] WHERE [ID] = " + LastInsertedId + " ;"; // update the table by giving to another row the value of the last inserted id
SqlCommand mySqlCommand2 = new SqlCommand(commandString2, SqlServerConnection);
mySqlCommand2.ExecuteNonQuery();
symbolPosition[0] = LastInsertedId; // mark the position of the new inserted symbol
ResultedSymbols.Add(symbolPosition); // add the new record to the results collection
}
}
catch (SqlException retrieveSymbolIndexException) // this is executed only if there were errors in the try block
{
Console.WriteLine("Error: {0}", retrieveSymbolIndexException.ToString()); // user is informed about the error
}
CreateSymbolTable(LastInsertedId); //(3) // Create new table based on the last inserted id
if (MyResultsTrace) SQLView.LogResult(LastInsertedId); // log the action
return ResultedSymbols; // return the list containing this new record
}
I tried the above but they didn't work, i found this thought, that works a just fine for me.
var ContactID = db.GetLastInsertId();
Its less code and i easy to put in.
Hope this helps someone.
You can also use a call to SCOPE_IDENTITY in SQL Server.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DBDemo2
{
public partial class Form1 : Form
{
string connectionString = "Database=company;Uid=sa;Pwd=mypassword";
System.Data.SqlClient.SqlConnection connection;
System.Data.SqlClient.SqlCommand command;
SqlParameter idparam = new SqlParameter("#eid", SqlDbType.Int, 0);
SqlParameter nameparam = new SqlParameter("#name", SqlDbType.NChar, 20);
SqlParameter addrparam = new SqlParameter("#addr", SqlDbType.NChar, 10);
public Form1()
{
InitializeComponent();
connection = new System.Data.SqlClient.SqlConnection(connectionString);
connection.Open();
command = new System.Data.SqlClient.SqlCommand(null, connection);
command.CommandText = "insert into employee(ename, city) values(#name, #addr);select SCOPE_IDENTITY();";
command.Parameters.Add(nameparam);
command.Parameters.Add(addrparam);
command.Prepare();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
int id = Int32.Parse(textBoxID.Text);
String name = textBoxName.Text;
String address = textBoxAddress.Text;
command.Parameters[0].Value = name;
command.Parameters[1].Value = address;
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
int nid = Convert.ToInt32(reader[0]);
MessageBox.Show("ID : " + nid);
}
/*int af = command.ExecuteNonQuery();
MessageBox.Show(command.Parameters["ID"].Value.ToString());
*/
}
catch (NullReferenceException ne)
{
MessageBox.Show("Error is : " + ne.StackTrace);
}
catch (Exception ee)
{
MessageBox.Show("Error is : " + ee.StackTrace);
}
}
private void buttonSave_Leave(object sender, EventArgs e)
{
}
private void Form1_Leave(object sender, EventArgs e)
{
connection.Close();
}
}
}
There are all sorts of ways to get the Last Inserted ID but the easiest way I have found is by simply retrieving it from the TableAdapter in the DataSet like so:
<Your DataTable Class> tblData = new <Your DataTable Class>();
<Your Table Adapter Class> tblAdpt = new <Your Table Adapter Class>();
/*** Initialize and update Table Data Here ***/
/*** Make sure to call the EndEdit() method ***/
/*** of any Binding Sources before update ***/
<YourBindingSource>.EndEdit();
//Update the Dataset
tblAdpt.Update(tblData);
//Get the New ID from the Table Adapter
long newID = tblAdpt.Adapter.InsertCommand.LastInsertedId;
Hope this Helps ...
After inserting any row you can get last inserted id by below line of query.
INSERT INTO aspnet_GameProfiles(UserId,GameId)
VALUES(#UserId, #GameId);
SELECT ##IDENTITY
If you're using executeScalar:
cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();
Maybe this answer helps as well as my database seems to have no column specified as "IDENTITY" (which is needed for "SELECT SCOPE_IDENTITY()" or "##IDENTITY" calls). Also my "ID" column was of type "binary(16)" so I needed to convert the output like stated below:
string returnId = BitConverter.ToString((byte[])cmd.ExecuteScalar()).Replace("-", "");
// skip the replace if you handle the hyphen otherwise
Use SELECT SCOPE_IDENTITY() in query
After this:
INSERT INTO aspnet_GameProfiles(UserId, GameId) OUTPUT INSERTED.ID VALUES(#UserId, #GameId)
Execute this
int id = (int)command.ExecuteScalar;
It will work
INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(#UserId, #GameId)";
then you can just access to the last id by ordering the table in desc way.
SELECT TOP 1 UserId FROM aspnet_GameProfiles ORDER BY UserId DESC.
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[spCountNewLastIDAnyTableRows]
(
#PassedTableName as NVarchar(255),
#PassedColumnName as NVarchar(225)
)
AS
BEGIN
DECLARE #ActualTableName AS NVarchar(255)
DECLARE #ActualColumnName as NVarchar(225)
SELECT #ActualTableName = QUOTENAME( TABLE_NAME )
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = #PassedTableName
SELECT #ActualColumnName = QUOTENAME( COLUMN_NAME )
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME = #PassedColumnName
DECLARE #sql AS NVARCHAR(MAX)
SELECT #sql = 'select MAX('+ #ActualColumnName + ') + 1 as LASTID' + ' FROM ' + #ActualTableName
EXEC(#SQL)
END
This question already has answers here:
If Exists Update Else Insert with VB.net (sql parameterised query)
(3 answers)
Closed 9 years ago.
I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
SqlCommand cmd = new SqlCommand("INSERT INTO Raspunsuri Values(#raspuns,#cnp,#data,'1',#ip,#idsesiune)", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
try
{
con.Open();
cmd.ExecuteNonQuery();
Response.Redirect("User2.aspx");
}
catch (Exception ex)
{
Console.WriteLine("Error:" + ex);
}
finally
{
con.Close();
}
What i need is to see if there is any record in the table and if there is than update else insert it.How can I achieve that?
This is probably best done in a Stored Procedure due to the amount of scripting involved (it would be messy inline!).
Pass your parameters to a Stored Procedure and do something like:
IF EXISTS(SELECT cnp FROM Raspunsuri WHERE cnp=#cnp)
BEGIN
UPDATE ...
WHERE cnp=#cnp
END
ELSE
BEGIN
INSERT INTO....
END
Assuming #cnp is your Primary Key
Your SqlCommand would then be changed to:
SqlCommand cmd = new SqlCommand("sp_StoredProcedureName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
You can use the Exists function in SQL. For Example
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
SqlCommand cmd = new SqlCommand("if Exists(Select 1 from Raspunsuri where <your unique criteria>)\r\n" +
"Update Raspunsuri set <values you want to set> where <your unique criteria\r\n" +
"else\r\n" +
"INSERT INTO Raspunsuri Values(#raspuns,#cnp,#data,'1',#ip,#idsesiune)", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
cmd.Parameters.AddWithValue("#raspuns", textbox1.Text);
cmd.Parameters.AddWithValue("#data", DateTime.Now.ToLocalTime());
cmd.Parameters.AddWithValue("#ip",ip);
cmd.Parameters.AddWithValue("#idsesiune", id_sesiune);
That should do the trick
You can use the ##ROWCOUNT feature from SQL Server.
UPDATE Raspunsuri SET (...) WHERE PrimaryKeyColumn='YourValue'
IF ##ROWCOUNT=0
INSERT INTO Raspunsuri VALUES (...)
Similar question: Insert / Update to Sql
What i need is to see if there is any record in the table and if there is than update else insert
it.How can I achieve that?
Write proper SQL?
Basiacll waht you need to forumlate is known as an "Upsert".
http://www.databasejournal.com/features/mssql/article.php/3739131/UPSERT-Functionality-in-SQL-Server-2008.htm
hasa good explanation.
First you check whether the record is present in the table by writing a query as "Select count(*) from tablename where columnvalue="something".If count is more than 0 then table has record.So in that case you write an Update statement else write Insert statement. This you can write in your code or by writing a stored procedure.
What i need is to see if there is any record in the table and if there
is than update else insert it.How can I achieve that?
I like #Alex's approach
-- For each row in source
BEGIN TRAN
UPDATE target
SET <target_columns> = <source_values>
WHERE <target_expression>
IF (##ROWCOUNT = 0)
INSERT target (<target_columns>)
VALUES (<source_values>)
COMMIT
I am dealing with the following problem:
I use a MSSQL Stored Procedure for displaying my data in a DataGridView. The Update and Insert Commands work, but there is one problem:
On inserting a new Row, the auto-numbered primary key isn't send back to my DataAdaptar. So the insertion is successfull in the database, but the PK is left blank in the DataGridView.
I allready tried some codes like:
private void _rowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.Status == UpdateStatus.Continue && e.StatementType == StatementType.Insert)
{
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT ##IDENTITY FROM " + e.Row.Table.TableName;
DataRow r = dt.Rows[dt.Rows.Count - 1];
r.ItemArray[0] = cmd.ExecuteScalar();
//r.SetModified(); --> err?
r.AcceptChanges();
}
}
on the DataAdapter, but nothing seems to work. All the SQL commands work fine.
When I refresh the data in the DataGridView, everyting is perfect. But the problem with this is, that the sort order and column width are adjusted. And that isn't what I want.
Can someone help me with this problem?
Looking forward for the solutions!
Thanks!
Finally found the answer and wanted to share it:
dt.RowChanged += new DataRowChangeEventHandler(_update_fields);
private void _update_fields(object sender, DataRowChangeEventArgs e)
{
try
{
if (e.Action == DataRowAction.Add)
{
conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "SELECT IDENT_CURRENT('" + e.Row.Table.TableName + "')";
dt.Rows[dt.Rows.Count - 1][0] = int.Parse(cmd.ExecuteScalar().ToString()) + 1;
dt.AcceptChanges();
conn.Close();
}
adapt.Update(dt);
}
catch (SqlException ex)
{
Debug.WriteLine(ex.Message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
Hope it will save you some time! :)
Gr
VeeWee
Since the connection to sql server has terminated so ##identity will become null and hence you are getting null value.
You cannot use scope_identity() here since its scope is limited to the place i.e. procedure in your case where it is called.
ident_current() always returns last identity value for the table that you specified.
It might not work correct in case of replication
Update your commandText to ="Select ident_current("+e.Row.Table.TableName+")"
Here are the results of using various techniques of retrieving identity value.
Replace dbo.M_PatientEntry with your table name
select ident_current('dbo.M_PatientEntry')
---------------------------------------
13
select ##identity from dbo.M_PatientEntry
---------------------------------------
NULL
NULL
select scope_identity()
---------------------------------------
NULL
select scope_identity() from dbo.M_PatientEntry
---------------------------------------
NULL
NULL
Also try avoiding ##Identity rather use scope_identity() or ident_current
##identity will give you incremented value of trigger table result if you are using trigger on the same table where insertion is going on.
see this documentation