Update one SQL table while Deleting from another - c#

I have two SQL tables (SalesCategory and ProductLine), each with two columns. A product category cannot be associated with a Sales Category and a Product Line at the same time. Users can, however, change, for example, Product Category ABC to be associated with Sales Category 123 instead of Product Line 456. When something like this happens, I want to remove the record of Product Category ABC from the ProductLine SQL table and UPDATE the SalesCategory with the ID of Product Category ABC. But I am not sure how to do this without making another separate DELETE function and calling them inside the save function for the SQL table in question. I feel like I'm putting in too many functions related to these 2 SQL tables....
As an important side note, Product Categories cannot be associated with more than one Product Line or more than one Sales Category.
Is there a better way to setup the code so I don't have a bunch of functions floating around associated with two SQL database tables? Or is this the best way to go about things?
Here is my code as it is now:
//Get current Product Line and Sales Cateogry data for the current Category.
//These two functions are called in the Page_Load
protected string getProductLine()
{
string retVal = "";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT ProductLine FROM ProductLine WHERE uidCategory = #CategoryID", cn);
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["ProductLine"].ToString() != "")
{
productLineTxt.Text = reader["ProductLine"].ToString();
retVal = productLineTxt.Text;
}
else
{
retVal = "";
}
}
}
cn.Close();
}
}
catch (Exception ex)
{
//
}
return retVal;
}
protected string getSalesCategory()
{
string retVal = "";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand("SELECT SalesCat FROM SalesCategory WHERE uidCat = #CategoryID", cn);
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (reader["SalesCat"].ToString() != "")
{
salesCatTxt.Text = reader["SalesCat"].ToString();
retVal = salesCatTxt.Text;
}
else
{
retVal = "";
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
//These two functions are called in the saveSalesCategory() and saveProductLine() functions respectively. They determine if those save functions should perform an UPDATE or INSERT. This is meant to prevent a Product Category from having association with more than one Product Line or Sales Category
protected bool salesCatExists()
{
bool retVal = true;
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT COUNT(*) AS 'Exists' FROM SalesCategory WHERE uidCat = #CategoryID";
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#SalesCategory", salesCatTxt.Text));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(reader["Exists"]) == 0)
{
retVal = false;
}
else
{
retVal = true;
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
protected bool productLineExists()
{
bool retVal = true;
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "SELECT COUNT(*) AS 'Exists' FROM ProductLine WHERE uidCategory = #CategoryID";
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#ProductLine", productLineTxt.Text));
cmd.CommandType = CommandType.Text;
using (IDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
if (Convert.ToInt32(reader["Exists"]) == 0)
{
retVal = false;
}
else
{
retVal = true;
}
}
}
cn.Close();
}
}
catch (Exception x)
{
//
}
return retVal;
}
//Save new or update old Product Line and Sales Category data for the current Category
protected void saveProductLine()
{
try
{
string update1 = "UPDATE ProductLine SET ProductLine = #ProductLine WHERE uidCategory = #CategoryID";
string update2 = "UPDATE ProductLine SET ProductLine = '' AND uidCategory = '' WHERE uidCategory = #CategoryID";
string insert = "INSERT INTO ProductLine (uidCategory, ProductLine) VALUES(#CategoryID, #ProductLine)";
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#ProductLine", productLineTxt.Text));
cmd.CommandType = CommandType.Text;
if (getProductLine() == "")
{
cmd.CommandText = insert;
}
else
{
productLineTxt.Text = getProductLine();
cmd.CommandText = update;
}
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception ex)
{
//
}
}
protected void saveSalesCategory()
{
string update = "UPDATE SalesCategory SET SalesCat = #SalesCategory WHERE uidCat = #CategoryID";
string insert = "INSERT INTO SalesCategory (uidCat, SalesCat) VALUES(#CategoryID, #SalesCategory)";
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AbleCommerce"].ToString()))
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add(new SqlParameter("#CategoryID", _CategoryId));
cmd.Parameters.Add(new SqlParameter("#SalesCategory", salesCatTxt.Text));
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
if (salesCatExists() == false)
{
cmd.CommandText = insert;
}
else
{
cmd.CommandText = update;
}
cmd.ExecuteNonQuery();
cn.Close();
}
}
catch (Exception x)
{
//
}
}

You might look into the SQL MERGE statement. I'm not sure I completely understand what you're hoping to do enough to give a code example of how it might help you, but that sounds like it might do something like your goal.
It'll let you, for instance, check one table (whether an actual table or just a table-valued-variable) against another given a key or set of keys, then take action when records match or when they don't match.
I suppose I can give a quick example, though:
This query could handle much of the logic in your saveSalesCategory method:
MERGE SalesCategory AS T
USING (VALUES ((#CategoryID, #SalesCategory)) AS S (uidCat, SalesCat)
ON (T.uidCat = S.uidCat)
WHEN MATCHED THEN
UPDATE SET SalesCat = S.SalesCat
WHEN NOT MATCHED THEN
INSERT (uidCat, SalesCat) VALUES (S.uidCat, S.SalesCat)
As you'll notice, it checks to see whether any records exist, then inserts or updates accordingly. This gets rid of your need to run salesCatExists() and use multiple TSQL queries.
I recognize that this doesn't answer your question (I think?) but I hope it at least guides you a bit in the right direction, since I'm still not overly sure what exactly you are looking for.

You can't have an update to one table and a delete to another table like this in a single command. It seems that the data structure is what you are fighting the most here. If your ProductCategory table had a column for ReferenceType this would be pretty simple. You would be able to update the ReferenceType and the foreign key value in a single pass. With they way you have put this together you also are going to have challenges with referential integrity because the value in ProductCategory would be a foreign to one or the other table depending on which type it is.

Your code sample looks like it isn't trying to do everything that you descriptions states. Maybe you just hadn't gotten to the delete part. I think a couple of stored procedures might be helpful. I condensed a couple of your methods into one stored proc, and you can do the same thing for the Product Line. I just wasn't sure where to put the DELETE statement. Is this the right direction? If so, we can figure out where to put that delete ;)
CREATE PROCEDURE SaveSalesCategory
#CategoryID INT ,
#SalesCategory INT
AS
BEGIN
DECLARE #SalesCatCount INT = ( SELECT COUNT(*) AS 'Exists'
FROM SalesCategory
WHERE uidCat = #CategoryID
)
IF #SalesCatCount = 0
BEGIN
INSERT INTO SalesCategory
( uidCat, SalesCat )
VALUES ( #CategoryID, #SalesCategory )
END
ELSE
BEGIN
UPDATE SalesCategory
SET SalesCat = #SalesCategory
WHERE uidCat = #CategoryID
END
END
GO

Use an OUTPUT clause (MSDN)
DELETE ProductLine
WHERE uidCategory = #CategoryID
OUTPUT column1,column2,etc INTO SalesCategory
or
DELETE SalesCategory
WHERE uidCategory = #CategoryID
OUTPUT column1,column2,etc INTO ProductLine

You could put a trigger on both of those tables so that when you insert a new record or update an existing record the DB looks to your other table for that category and deletes that record.
Not all of your parameters were used in your example code and it's kind of long so I don't think this code, as written, will do exactly what you need but the concept I think should work.
CREATE TRIGGER dbo.TRG_SalesCategory_RECORD
ON SalesCategory
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
Delete from ProductLine
Where CategoryID = (select CategoryID from INSERTED)
END
GO
CREATE TRIGGER dbo.TRG_ProductLine_RECORD
ON ProductLine
AFTER INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON;
Delete from SalesCategory
Where CategoryID = (select CategoryID from INSERTED)
END
GO

Related

Syntax error in update using C# inputting data into an existing row

I am having problem with my code with the update query it shows the error syntax error in update statement. I would like to insert in data into an existing row with the columns already created.
private void save_care_Click(object sender, EventArgs e)
{
if (textBox2.Text=="")
{
//Checking if workorder exist in database
connection.Open();
OleDbCommand checkrecord = new OleDbCommand("SELECT COUNT(*) FROM [c# barcode] WHERE ([Workorder] = #workorder)", connection);
checkrecord.Parameters.AddWithValue("#workorder", textBox2.Text);
int recordexist = (int)checkrecord.ExecuteScalar();
if (recordexist > 0)
{
//add data if it exist
string cmdText = "UPDATE [c# barcode] SET ([Close from care],[Name care]) VALUES (#Close, #name) WHERE ([Workorder] = #workorder)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
cmd.ExecuteNonQuery();
textBox2.Clear();
connection.Close();
}
connection.Close();
}
else
{
//inserting workorder if it does not exist
string cmdText = "INSERT INTO [c# barcode] ([Workorder], [Close from care], [Name care]) VALUES (#workorder, #Close, #name)";
using (OleDbCommand cmd = new OleDbCommand(cmdText, connection))
{
cmd.Parameters.AddWithValue("#workorder", textBox2.Text);
cmd.Parameters.AddWithValue("#Close", DateTime.Now.ToString("d/M/yyyy"));
cmd.Parameters.AddWithValue("#name", label4.Text);
if (cmd.ExecuteNonQuery() > 0)
{
textBox2.Clear();
MessageBox.Show("Insert successful, workorder has not been handed over, please check");
}
else
{
textBox2.Clear();
MessageBox.Show("Please rescan");
connection.Close();
}
connection.Close();
}
}
}
else
MessageBox.Show("No data, Please scan workorder");
}
Error is at cmd.ExecuteNonQuery(); line.
For example the table in the picture under workorder there is a test4 the update will insert data into the column [Close from care] and [name care] in the test4 row
I believe that you are using the INSERT syntax for an UPDATE. You should use the UPDATE syntax.
The example from Microsoft is as follows:
UPDATE Orders
SET OrderAmount = OrderAmount * 1.1,
Freight = Freight * 1.03
WHERE ShipCountry = 'UK';
So if we update yours to match, it should look like this:
UPDATE [c# barcode]
SET [Close from care] = #Close,
[Name care] = #name
WHERE [Workorder] = #workorder
Obviously the newlines aren't important, it's just to make it easier to read.

Updating multiple rows with the same Ordernumber

I'm trying to update values of two tables such as from dataGridview
Order table and Orderdetail table as shown in my image.
It's working to update Order table but updating OrderdDetail table is not working. I want to update all rows with the same OrderNr. I get OrderDetail values from dataGridView. Here is my code:
private void UpdateOrder(int paymentTypes)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["Db"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("UPDATE [Orders] SET Amount = #Amount, Tax = #Tax , ToPay = #ToPay WHERE OrderNr = #OrderNumber", conn))
{
// This First table Orders updating fine
cmd.Parameters.AddWithValue("#Amount", txtAmount.Text);
cmd.Parameters.AddWithValue("#Tax", txtTax.Text);
cmd.Parameters.AddWithValue("#ToPay", txtToPay.Text);
cmd.ExecuteNonQuery();
}
// Here begin for OrderDetails table and not working to update.
foreach (DataGridViewRow row in dgvCart.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("UPDATE [OrdersItems] SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity, WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
{
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Updating successfully !", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
There are a couple of errors in your code.
First you have a syntax error in your query
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET OrderNr = #OrderNumber, ProductId = #ProductId, Quantity = #Quantity,
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
There is a comma before the WHERE statement that you should remove.
Second, the first query is missing the parameter for OrderNumber.
Third point.
In OleDb parameters are positional, even if you can name them you should put them in the same order in which they appear in the query and you need to put it again if you use them two times (OrderNumber & ProductID appear both in the SET part and in the WHERE)
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));
However you don't need to update the ProductID and the OrderNumber. They cannot change otherwise this query could not find the rows that you want to update.
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE [OrdersItems]
SET Quantity = #Quantity
WHERE OrderNr = #OrderNumber AND ProductId = #ProductId", conn))
with only three parameters in the correct order
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt32(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#OrderNumber", txtOrderNumber.Text);
cmd.Parameters.AddWithValue("#ProductId", Convert.ToDecimal(row.Cells["ProductId "].Value));

How to check in an insert into command in SQL Server using C#

I have 3 tables: Student, Books and Borrows:
Student (id, name, FK_borrow)
Books (id, name, nbre_books_available int)
Borrows (borrow_from, borrow_to, FK_student, FK_books)
I want to insert values into the table Borrows after checking if the column nbre_books_available is not 0, and update it.
This my attempt
private void fillborrow()
{
cmd.Connection = cn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into borrows Values ('"+dateTimePicker1.Value+"','"+dateTimePicker2.Value+"',"+int.Parse(textBox1.Text)+","+int.Parse(textBox2.Text)+")" ;
cn.Open();
int a = cmd.ExecuteNonQuery();
cn.Close();
if (a == 0)
{
MessageBox.Show("Erreur");
}
else
{
MessageBox.Show("Ajouter avec success");
}
cmd.CommandText = "update books set nbre_current = nbre_current - 1 where CodeO = " + int.Parse(textBox1.Text);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
I don't know how to Add the requete that check if the nbre_books_available column is 0 or not
This is essentially the same question as this
You can perform your exist check at the same time as inserting and then check the return value of ExecuteNonQuery().
If it returns 0 then no rows were inserted, otherwise it was successful.

Error in ado.net crud operations

I want to update details. I have code in a data access class. But after executing ExecuteScalar(), it goes to the catch block and shows an exception as null.
Program :
public bool UpdateData(Customer objcust) // passing model class object because it contains all customer properties.
{
SqlConnection con = null;
// string result = "";
//int rows = 0;
try
{
string connectionString = #"server=(local)\SQLExpress;database=CustDemo;integrated Security=SSPI;";
con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE Customer SET Name = #Name , Address = #Address, Gender =#Gender , City=#City WHERE Customer.CustomerID = #CustomerID",con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", objcust.Name);
cmd.Parameters.AddWithValue("#Gender", objcust.Gender);
cmd.Parameters.AddWithValue("#Address", objcust.Address);
cmd.Parameters.AddWithValue("#City", objcust.City);
con.Open();
cmd.ExecuteScalar();
return true;
}
catch(Exception ex)
{
return false;
}
}
Instead of cmd.ExecuteScalar(); Try to use
cmd.ExecuteNonQuery ();
ExecuteNonQuery is used specifically executing UPDATE, INSERT, or DELETE statements.

Retrieving ID while having only user_name

I'm trying to make a private message system.
What I have so far.
- checking if player exists with the name from textbox, if not, error shows up.
Now, I'm trying to insert it to the table. The problem is that the table have 2 colums
to_user_id
from_user_id
And becasuse I'm using a textbox to enter the name of the user, I dont how to retrieve to_user_id from users table while having only name.
this is my code
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString());
conn.Open();
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
if (flag == true)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
}
else if(flag == false)
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connect"].ToString()))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = #"INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #to, #from, #date)";
cmd.Parameters.AddWithValue("#title", TextBox_Title.Text);
cmd.Parameters.AddWithValue("#content", TextBox_Msg.Text.Replace("\n", "<br/>"));
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
cmd.Parameters.AddWithValue("#date", DateTime.Now);
cmd.Parameters.AddWithValue("#from", Session["id"].ToString());
con.Open();
cmd.ExecuteNonQuery();
}
}
Of course I got an error
Conversion failed when converting the nvarchar value 'username' to data type int.
#edit,
#cordan I tried this
DECLARE #user_id = (SELECT id FROM users WHERE user_login=#to );
INSERT INTO messages (message_title, message_content, to_user_id, from_user_id, message_date)
VALUES (#title, #content, #user_id, #from, #date);
cmd.Parameters.AddWithValue("#to", TextBox_To.Text);
got this error
Incorrect syntax near '='.
Must declare the scalar variable "#user_id".
This bit here is a huge NO!!
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select * from [users]";
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
while (rd.Read())
{
if (rd[1].ToString() == TextBox_To.Text)
{
flag = false;
break;
}
}
conn.Close();
You are selecting every single user from the users table, just to determine if the one you're trying to find exists.
Aside from the fact that you could almost certainly just add:
if (rd[1].ToString() == TextBox_To.Text)
{
foundUserId = (int)rd[0]; // I'm assuming the first column in users is the Id - it probably is
flag = false;
break;
}
DONT DO THAT!!
Instead, you should just be looking for the one username you're interested in
SqlCommand cmdd = new SqlCommand();
cmdd.CommandText = "select top 1 Id from [users] where username=#username";
cmdd.Parameters.AddWithValue("#username",username);
cmdd.Connection = conn;
SqlDataReader rd = cmdd.ExecuteReader();
var userId = 0;
if(rd.Read())
{
userId = (int)rd[0];
}
conn.Close();
if (userId == 0)
{
Label1.Visible = true;
Label1.Text = "User does not exist";
return;
}
else
.... // userId holds the users Id
...
cmd.Parameters.AddWithValue("#to", userId);

Categories

Resources