How to use insert and update command using c# - c#

I have GridView and I am trying to check Task_ID from a table, if it is found then I want to update the record but if Task_ID is not found in the table then I want to insert it into my table. My code now does the insert part but it does not do the update part of the code. I was wondering how you can do this within the same code. Please help. thanks
here is my code:
int index = 0;
foreach (GridViewRow row in myGV.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label ID = row.FindControl("lbl_ID") as Label;
string UID = Request.Form[row.FindControl("hfUId").UniqueID];
DateTime strDate = DateTime.Now;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myCon"].ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into myTable(TID, USR_ID, UPDT_DT) values(#ID, #USR_ID, #UPDT_DT) ";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("#USR_ID", SqlDbType.VarChar).Value = UID.ToString();
cmd.Parameters.Add("#UPDT_DT", SqlDbType.VarChar).Value = strDate.Date;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
cmd.Dispose();
}
index++;
}

There is a MERGE command in SQL for this purpose. Here is an example that might work for you:
Merge myTable As T
Using (Select Task_ID From myTable) As Src (Src_ID)
ON (T.Task_ID = Src.Src_ID)
WHEN MATCHED THEN
UPDATE SET T.UPDT_DT = 'your new value'
WHEN NOT MATCHED THEN
INSERT (TASK_ID, USR_ID, UPDT_DT)
VALUES (#TASK_ID, #USR_ID, #UPDT_DT);
change 'your new value' to the correct update statement

Replace the command text as below:
if not exists (select task_id from mytable where task_id = #task_id)
insert into myTable(TASK_ID, USR_ID, UPDT_DT) values(#TASK_ID, #USR_ID, #UPDT_DT)
else
update mytable set USR_ID = #USR_ID, UPDT_DT = #UPDT_DT where task_id = #TASK_ID

I would first query the database to see if the task_id existed... declare cmd, define it with a sql command like "Select count(*) from myTable where Task_ID = '" & Task_ID.text & "'" and assign that to some variable x. Then follow that with "if x <> 0 then --> define your cmd as an insert statement here, ELSE --> define cmd as "Update myTable set blah blah = values WHERE task_ID = " & task_ID.text.

Related

Get the identity of the last updated row in SQL via C#

I am trying to first create a new row in my SQL Compact Edition database via C# and then I want to update the same row with information in my radiobuttons. I have an "ID" column in the database which is auto incremental.
So I tried to assign its value to a variable using ##Identity and call it in the update query but it doesn't work. I've tried MAX to find the max value in ID column which will be the latest row but it still didn't work. Here's my code.
con.Open();
string sqlAdd = "Insert into MembersTable ([First Name],Surname,[Middle Name])
Values('"+txtFirstName.Text+"','"+txtSurname.Text+"','"+ txtMiddleName.Text+"')";
string IDIdentifier = "Select ##Identity AS TempID";
string sqlgenderM = "Update MembersTable set Gender='M' where ID='" + DC.ID + "'";
string sqlgenderF = "Update MembersTable set Gender='F' where ID='" + DC.ID + "'";
com = new SqlCeCommand(sqlAdd, con);
com.ExecuteNonQuery();
SqlCeCommand com1 = new SqlCeCommand(IDIdentifier, con);
SqlCeDataReader dr1 = com1.ExecuteReader();
if (dr1.Read())
{
DC.ID = dr1["TempID"].ToString();
}
{
if (rbGenderMale.Checked == true)
{
SqlCeCommand gendercom = new SqlCeCommand(sqlgenderM, con);
gendercom.ExecuteNonQuery();
}
else if (rbGenderFemale.Checked == true)
{
SqlCeCommand gendercom = new SqlCeCommand(sqlgenderF, con);
gendercom.ExecuteNonQuery();
}
}
The fields (First Name, Middle Name, Surname) get updated but the Gender columns don't. What am I doing wrong?
Thanks to #Soner I used:
int.TryParse(dr1["TempID"].ToString(), out Identity);
string IdentityS = Identity.ToString();
and replaced DC.ID with IdentityS
Now it works perfectly.

Read Id of last inserted

I have been through everything for a couple weeks now only to find statements working at the database level. Below is my code and I feel that I am very near the answer but keep getting -1 returned from SCOPE_IDENTITY(). Customer_Name is saving to the table just fine along with the auto increment. I just need the Customer_ID so that I can place it in the Customer_Address table for the one to many identification of the address to the customer.
Thanks in advance for your help.
if (customer_ID == "")
{
// add new customer
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name)";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
// get last inserted Customer_ID
string SQL_customerId = "SELECT SCOPE_IDENTITY()";
SqlCommand sqlCommand_customerId = new SqlCommand(SQL_customerId, sqlConnection);
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
sqlCommand_customerId.ExecuteNonQuery();
// string SQL_ = "SELECT Customer_ID FROM Customer";
// SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
// int maxId = Convert.ToInt32(sqlCommand.ExecuteScalar());
sqlConnection.Close();
}
You need to have the SCOPE_IDENTITY within the same transaction as your insert. The following should help you.
string SQL = "INSERT INTO Customer (Customer_Name) VALUES (#customer_Name); SELECT Customer_Id FROM Customer WHERE Customer_Id = SCOPE_IDENTITY();";
SqlCommand sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add("#customer_Name", SqlDbType.VarChar, 100).Value = customer_Name;
sqlConnection.Open();
int id = (int) sqlCommand.ExecuteScalar();
try something like this..
Output clause will help you to get the inserted value and with that we can insert into another temp or physical table. This is just an idea to your question
CREATE TABLE customer
(
id INT IDENTITY(1, 1),
addres VARCHAR(500)
)
CREATE TABLE customeraddrs
(
custid INT
)
INSERT INTO customer
output inserted.id
INTO customeraddrs
VALUES ('a'),
('b')
SELECT *
FROM customer
SELECT *
FROM customeraddrs

Try to store the data into sqlserver

i want to store the data in sqlserver and i'm able with this code.Now i want to check if table is exists than insert the data or create new table and insert the data..So i need help...thnku
SqlConnection con = new SqlConnection("Data Source=PRAWAT; Initial Catalog=StudentData ;Integrated security=true; ");
string query = "insert into NewValidStudentData(StudentId,Name,Marks) values (#StudentId,#Name,#Marks);";
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(query, con);
con.Open();
da.InsertCommand.Parameters.Clear();
da.InsertCommand.Parameters.AddWithValue("#StudentId", System.Data.SqlDbType.NVarChar).Value = value[0];
da.InsertCommand.Parameters.AddWithValue("#Name", System.Data.SqlDbType.NVarChar).Value = value[1];
da.InsertCommand.Parameters.AddWithValue("#Marks", System.Data.SqlDbType.NVarChar).Value = value[2];
da.InsertCommand.ExecuteNonQuery();
con.Close();
You can edit your query to something like:
IF (EXISTS
(SELECT * FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'YourSchemaName'// if you don't know the name, try 'dbo'
AND TABLE_NAME = 'NewValidStudentData'))
BEGIN
INSERT INTO NewValidStudentData(StudentId, Name, Marks)
VALUES (#StudentId, #Name, #Marks);";
END
Just wrap this query as a string and execute the same. This way, you can control the table's existence and insert the data within a single call to database server.
First check if your table exists with this snippet (also see this answer):
bool exists;
string tableName = "WhatEverItIs";
try {
// ANSI SQL way. Works in PostgreSQL, MSSQL, MySQL.
var cmd = new OdbcCommand(
"select case when exists((select * from information_schema.tables where table_name = '" + tableName + "')) then 1 else 0 end");
exists = (int)cmd.ExecuteScalar() == 1;
} catch {
try {
// Other RDBMS. Graceful degradation
exists = true;
var cmdOthers = new OdbcCommand("select 1 from " + tableName + " where 1 = 0");
cmdOthers.ExecuteNonQuery();
} catch {
exists = false;
}
}
Then if it wasn't exist:
if(!exists) {
var createTableSql = "CREATE TABLE WHAT_YOUR_TABLE_SCHEME_IS";
// execute a command with above createTableSql, to create your table
}
And then, do the rest of your code
StudentId as NVARCHAR? Does Student Id has characters in it?
IF NOT EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[NewValidStudentData]') AND type in (N'U'))
BEGIN
CREATE TABLE [dbo].[NewValidStudentData](
StudentId NVARCHAR(10),
Name NVARCHAR(100),
Marks NVARCHAR(3)
)
END
Note: I would suggest handle this in stored procedure instead of writing all this in c# code.

How to check if a value already exists in my database and show a validation message

I have the below code, that connects to a Sql database and insert's data into a table :
string firstNameV = txtFname.Text;
string surnameV = txtSname.Text;
string emailV = txtEmail.Text;
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)";
cmd.Parameters.Add("#Title", SqlDbType.NVarChar).Value = title;
cmd.Parameters.Add("#FirstName", SqlDbType.NVarChar).Value = firstNameV;
cmd.Parameters.Add("#Surname", SqlDbType.NVarChar).Value = surnameV;
cmd.Parameters.Add("#Email", SqlDbType.NVarChar).Value = emailV;
cmd.Parameters.Add("#EstablishmentType", SqlDbType.NVarChar).Value = eType;
cmd.Parameters.Add("#Interests", SqlDbType.NVarChar).Value = ins;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
How do I check if an email being entered in the "txtEmail" text box already exists in my database, in the email column and then alert message saying email already exists so it doesn't get inserted into my database?
Call this method in required textbox or area
public void EmailCheck()
{
string constring = ConfigurationManager.ConnectionStrings["ConnData"].ConnectionString;
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from EmailSignUp where EmailId= #EmailId", con);
cmd.Parameters.AddWithValue("#EmailId", this.txtEmail.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("EmailId = " + dr[5].ToString() + " Already exist");
txtEmail.Clear();
break;
}
}
}
Try this
cmd.CommandText = "IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email = '"
+ txtEmail.Text + "')
BEGIN
INSERT INTO EmailSignUp (Title,FirstName,Surname,Email,EstablishmentType,Interests) VALUES (#Title,#FirstName,#Surname,#Email,#EstablishmentType,#Interests)
END";
Call a stored Procedure and inside the stored procedure you can check
before insert
IF NOT EXISTS(SELECT * FROM EmailSignUp WHERE Email =#email)
Begin
insert query here
end
In another way you can check it in text changed event also
Create a procedure on SQL server and check whether the name exists or not
CREATE PROCEDURE Procedure_Name
#mystring varchar(100),
#isExist bit out
AS
BEGIN
if exists(select column1 from tblTable1 where column1=#mystring)
begin
select #isExist=1
end
else
begin
select #isExist=0
end
END
GO
This is a sample procedure. If #isExist=1 that means the value exist.otherwise not. create a method to call this procedure and go on...
Happy Coding
This works for me:
Create a function Called CheckMail(string email)
public bool CheckMail(string email)
{
SqlConnection con = new SqlConnection("Data Source=*******; Initial Catalog=Your Database Name; Persist Security Info=True;User ID=****; Password=******");
SqlCommand cmd = new SqlCommand("select email from Table Name where email='"+email+ "'",con);
con.Open();
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.Read())
{
return false;
}
else
{
return true;
}
}
Then Implement in Button Click as
Pass Textbox value in function that were created..
if (CheckMail(EmailTxt.Text))
{
Write Your insert code to database
}
else
{
Error Message or Alert to Show Already Exists in database
}

How to assign a data column value to specific word using C#

I have a field in my table in which I would like to set a string like “COMPLETE”. Initially the field is empty and I want to set it some kind of text like “COMPLETE” Here is what I have so far…
string ID = GV_Action.Rows[0].Cells[1].Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("sp_Update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
in my Strored procedure below i am using a default ID but would like to pass the paramter ID and not use the fixed value how can i do that?
here is how i created the proc
CREATE PROC sp_Update
AS
EXEC msdb.dbo.sp_start_job N'UpdateField';
GO
EXEC sp_Update
and here is job that i am calling when the procedure kicks off
update MyTable
set Status = 'Complete'
where Post_ID = 303
You can fill it directly from database by
SELECT Count(*), 'COMPLETE' AS MyColumn FROM MyTable

Categories