Avoid Insert Duplicate data to db:asp.net - c#

I want to insert a course to my database table that has StudentId and CourseId fields.
and I don't want to insert a duplicate course to each student.
I use the below code for this. but if once I insert just one course for each student after running the program it shows to me "This unit has already been registered in the database"
//Avooid Insert Duplicate StudentId data to db
DataSet ds = new DataSet();
SqlCommand CmdDuplicate = new SqlCommand("select * from EDU_Student_Course_Registration where StudentId Like N'%" + LblStudentId.Text + "%'", con);
SqlDataAdapter da = new SqlDataAdapter(CmdDuplicate);
da.Fill(ds);
int j = ds.Tables[0].Rows.Count;
//int s=ds
//Avooid Insert Duplicate CourseId data to db
DataSet ds2 = new DataSet();
SqlCommand CmdDuplicate2 = new SqlCommand("select * from EDU_Student_Course_Registration where CourseId Like N'%" + LblCourseId.Text + "%'", con);
SqlDataAdapter da2 = new SqlDataAdapter(CmdDuplicate2);
da2.Fill(ds2);
int j2 = ds.Tables[0].Rows.Count;
if (j > 0 && j2 > 0)
{
string myStringVariable1 = "This unit has already been registered in the database";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable1 + "');", true);
ds.Clear();
ds2.Clear();
}
else
{
//// insert the data of [EDU_Student_Course_Registration] Table
string Sqlstr_SSLesson = " Insert Into EDU_Student_Course_Registration (" + " StudentId," + " CourseId," + " CreateDate " + " ) " +
"VALUES ('" + Int32.Parse(LblStudentId.Text) + "' ,'" + Int32.Parse(LblCourseId.Text) + "','" + obj.CreateDateTime() + "')";
sqlcom.CommandText = Sqlstr_SSLesson;
con.Open();
sqlcom.Connection = con;
sqlcom.ExecuteNonQuery();
sqlcom.Connection.Close();
string myStringVariable = "Your information has been successfully recorded";
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + myStringVariable + "');", true);
}
How I wanna do it right؟!

Your current tests: does it exist any row in this table with this studentId, whatever the course + does it exist any row in this table for this courseId, whater the student.
Change it for a single test : does it exist any row in this table for this studentId AND this courseId.

Related

SQL TOP 1 query when generating random ID with C# application [duplicate]

This question already has answers here:
Execute Insert command and return inserted Id in Sql
(8 answers)
Closed 3 years ago.
I have a C# application which creates an entry in the SQL database to table_customer_invoice and table_customer_invoice_detail, when a user sells a particular item from the application, as soon as the user enters the amount tendered, an insert in the customer_invoice table is done where ID is an identity column which I use that ID by reading the last entered ID by (SELECT TOP 1 ID FROM CUSTOMERINVOICE ORDER BY ID DESC) to insert in the table_customer_invoice_detail.
It works well the only problem is when two users sell an item together at the exact same time from different computers than the (SELECT TOP 1 ID) clashes and both users get the same ID as it looks for the last ID created. Is there any other way I can get the exact ID for the particular user?
This is the code in the application
SqlCommand cmd3 = new SqlCommand("insert into CUSTOMERINVOICE(INVOICEDATE,INVOICESTATUS,ISDEBTORINVOICE,ISLAYBYEINVOICE,INVOICETYPE,INVOICETOTAL,salesrep,dayended)" + "values(GETDATE(),0,0,0,1,'" + Convert.ToDecimal(lblTotalAmount.Text.ToString()) + "','" + txtSalesRep.Text + "',0)", conn);
cmd3.ExecuteNonQuery();
SqlDataAdapter ada2 = new SqlDataAdapter("SELECT TOP 1 ID FROM CUSTOMERINVOICE ORDER BY ID DESC", conn);
DataTable dt2 = new DataTable();
ada2.Fill(dt2);
DataRow dr2 = dt2.Rows[0];
CUSTID = Int32.Parse(dr2["ID"].ToString());
foreach (DataGridViewRow row in dgSaleBasket.Rows)
{
SqlDataAdapter ada5 = new SqlDataAdapter("SELECT itemcode,onhand,costincl FROM stmast where itemcode ='" + row.Cells[1].Value + "'", conn);
DataTable dt5 = new DataTable();
ada5.Fill(dt5);
int quantityPurchased = Int32.Parse(row.Cells[4].Value.ToString());
for (int i = 0; i < dt5.Rows.Count; i++)
{
DataRow dr5 = dt5.Rows[i];
double SellPrice = Convert.ToDouble(row.Cells[5].Value.ToString());
costinc = Convert.ToDouble(dr5["costincl"].ToString());
profit = (SellPrice - costinc) * quantityPurchased;
totalprofit = profit + totalprofit;
SqlCommand cmd4 = new SqlCommand("insert into CUSTOMERINVOICEDETAIL(INVOICEID,ITEMCODE,DESCRIPTION,QUANTITY,PRICE,profit,refund)" + "values(" + CUSTID + ",'" + row.Cells[1].Value.ToString() + "','" + row.Cells[2].Value.ToString() + "'," + row.Cells[4].Value.ToString() + ",'" + Convert.ToDecimal(row.Cells[5].Value.ToString()) + "'," + profit + ",0)", conn);
cmd4.ExecuteNonQuery();
SqlCommand cmd6 = new SqlCommand("UPDATE stmast SET onhand =onhand-" +quantityPurchased + ", lastSold =GETDATE() , lastSoldPrice=" + Convert.ToDecimal(row.Cells[5].Value.ToString()) + ",totalQtySold=totalQtySold+" + quantityPurchased + " WHERE itemcode ='" + row.Cells[1].Value + "'", conn);
cmd6.ExecuteNonQuery();
SqlCommand cmd2 = new SqlCommand("UPDATE customerinvoice set invoiceprofit=" + totalprofit + " WHERE id =" + CUSTID, conn);
cmd2.ExecuteNonQuery();
}
Maybe you can try by using INSERTED temporary table
example :
CREATE DATABASE TEST
USE TEST
CREATE TABLE client
(
id INT IDENTITY(1,1),
name varchar(20)
)
DECLARE #tempTable TABLE(id INT,
[name] varchar(20))
INSERT client(name)
OUTPUT INSERTED.* INTO #tempTable
VALUES ('Marc');
SELECT * FROM #tempTable
-- Return |1|Marc|

How to add multiple rows to SQL Server using Asmx web service?

I am currently working on a task which takes student information through web service and saves it to database. I have successfully implemented the task for adding single student information, but I want to add multiple students at runtime using the same web method.
Here is the code:
public string insertStudent(int id,string f_name , string l_name)
{
var con = new SqlConnection(ConnectionState());
con.Open();
string insert = "INSERT INTO STUDENT(std_id, first_name,last_name)";
//var cmd = new SqlCommand("Insert into [Student](std_id,first_name, last_name,) values('" + id + "','" + f_name + "','" + l_name+ "')", con);
insert += " VALUES (";
insert += "'" + id + "'";
insert += ", '" + f_name + "'";
insert += ", '" + l_name + "'";
insert += ")";
var cmd = new SqlCommand(insert, con);
cmd.ExecuteNonQuery();
string result = "Data Added to Database";
con.Close();
return result;
}

Query doesn't store my registration form data asp.net

I actually new in asp.net c# I want to know why this code below doesn't work.
All I want to do is store data form into a SQL Server database.
I have 2 tables and I want the data form entered stored in the database. Look at the select statement for retrieving the primary key to store it as a foreign key in the other table
String q = "Insert into dbo.requests(request_date,request_type,visit_date,reason,user_id,status_id)values('" + DateTime.Now.ToString() + "','" + DropDownList1.SelectedValue.ToString() + "','" + TextBox8.Text.ToString() + "','" + TextBox9.Text.ToString() + "','"+ 1+"','"+ 2+"')";
SqlCommand cmd = new SqlCommand(q, con);
cmd.ExecuteNonQuery();
con.Close();
con2.Open();
if (con2.State == System.Data.ConnectionState.Open)
{
String a = "select top 1 request_id from dbo.requests where request_date= CAST(GETDATE() AS DATE and user_id=999 order by request_id DESC ";
SqlCommand cmd2 = new SqlCommand(a, con2);
int r = cmd2.ExecuteNonQuery();
}
con2.Close();
con3.Open();
if (con3.State == System.Data.ConnectionState.Open)
{
String b = "INSERT into dbo.visitor(visitor_Fname,visitor_Mname,visitor_family_name,visitor_id,visitor_mobile,request_id,place_of_work,country_name) values ('" + TextBox1.Text.ToString() + "','" + TextBox2.Text.ToString() + "','" + TextBox3.Text.ToString() + "','" + TextBox4.Text.ToString() + "' , '" + TextBox5.Text.ToString() + "','r', '" + TextBox6.Text.ToString() + "', '" + TextBox7.Text.ToString() + "' )";
SqlCommand cmd3 = new SqlCommand(b, con3);
cmd3.ExecuteNonQuery();
}
You should change it
int r = cmd2.ExecuteNonQuery();
to
int r = (int)cmd2.ExecuteScalar();
To retrieve selecting only one field use ExecuteScalar instead of ExecuteNonQuery. ExecuteNonQuery doesn't return selecting fields.
Just store request_id in variable using data table.
Actually you are storing 'r' in table which is wrong. Try to store request_id from select statement in variable it will be work .

Why do I receive a incorrect syntax error while creating a table in C#

I am trying to create a table with the header which was read from a CSV file:
myConnection = new SqlConnection(cString);
myConnection.Open();
var lines = File.ReadLines(textBox1.Text);
List<string> readHeader = lines.ElementAt(0).Split(',').ToList();
string tab = "a123CSV";
readHeader.ToArray();
string exists = null;
try
{
SqlCommand cmd = new SqlCommand("SELECT * FROM sysobjects where name = '" + tab + "'", myConnection);
exists = cmd.ExecuteScalar().ToString();
}
catch (Exception ce)
{
exists = null;
}
if (exists == null)
{
int p;
for (p = 0; p <= readHeader.Count; p++)
{
if (exists == null)
{
SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p] + "] varchar(MAX))", myConnection);
createTable.ExecuteNonQuery();
exists = tab;
}
else
{
SqlCommand addcolumn = new SqlCommand("ALTER TABLE '" + tab + "' ADD [" + readHeader[p] + "] varchar(MAX)", myConnection);
addcolumn.ExecuteNonQuery();
}
}
}
The header in the CSV file is this:
"NPI","Entity Type Code","Replacement NPI","Employer Identification
Number (EIN)","Provider Organization Name (Legal Business
Name)","Provider Last Name (Legal Name)","Provider First
Name","Provider Middle Name","Provider Name Prefix Text"
Whenever I run my application I keep getting this error on this line:
...
if (exists == null)
{
SqlCommand createTable = new SqlCommand("CREATE TABLE '" + tab + "' ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);
createTable.ExecuteNonQuery();
...
Error:
Incorrect syntax near `a123CSV`
How can I resolve the error?
You need to escape the table name with [ and ] instead of single quotes, i.e.:
"CREATE TABLE [" + tab + "] ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))"
That is because you are enclosing TABLE_NAME inside single quotes. Use this,
SqlCommand createTable = new SqlCommand("CREATE TABLE " + tab + " ([" + readHeader[p].Replace("\"", "") + "] varchar(MAX))", myConnection);

Copy table content to another table in the same database with C#

Copy table content to another table in the same database with C#.
I got one database (Baza) with some data in two tables NEW and OLD. I need to periodically move NEW data to OLD data table (after I do some measuring). I need to compare these data in next step.
I'm using SQL Server CE wit Baza.sdf file. In any sophisticated way to copy table to table do it (some loop doing it automatically)?
Thanks
I solved it in this way:
Program reads in loop table NEW row by row and each value changes to parameter. I got 8 columns so 8 parameters(7 integers and one string)
Next each of parameter is inserted to OLD table.
Resuld is also displayed in textBox1:
SqlCeConnection conn = new SqlCeConnection("Data Source = \\Program Files\\My Program\\Program.sdf; Password ='mypassword'");
conn.Open();
try
{
SqlCeCommand cmd = new SqlCeCommand("SELECT * FROM [NEW]", conn);
SqlCeDataReader rdr = cmd.ExecuteReader();
cmd.Connection = conn;
cmd.ExecuteNonQuery();
while (rdr.Read())
{
int param1 = rdr.GetInt32(0);
int param2 = rdr.GetInt32(1);
int param3 = rdr.GetInt32(2);
int param4 = rdr.GetInt32(3);
int param5 = rdr.GetInt32(4);
int param6 = rdr.GetInt32(5);
int param7 = rdr.GetInt32(6);
string param8 = rdr.GetString(7);
textBox1.AppendText(" " + param1 + " " + param2 + " " + param3 + " " + param4 + " " + param5 + " " + param6 + " " + param7 + " " + param8);
textBox1.AppendText(System.Environment.NewLine);
SqlCeCommand ins = new SqlCeCommand("insert into [OLD] values ('" + param1 + "','" + param2 + "','" + param3 + "','" + param4 + "','" + param5 + "','" + param6 + "','" + param7 + "','" + param8 + "');");
ins.Connection = conn;
ins.ExecuteNonQuery();
}
}
catch (Exception msg)
{
MessageBox.Show(msg.ToString());
}
conn.Close();
What's wrong with:
insert into [table] (field1, field2)
select field1, field2 from [table2] where (your conditions are met)
? :-)
Since that's not supported in CE, thanks #marc_s, you could get the records from the NEW table using a select, then insert them into the OLD table, and then loop through the initial recordset to delete the rows from the NEW by ID for example.
Adding to what CodeCaster stated,
Put his code in a storedprocedure and create a job to run on a set interval of your choosing.
You can add logic to the storedprocedure to check the validity of the data as well and set it to notify you if the data was incorrect. Examples could be given if you included a more specific information in your question.

Categories