Click here to Skip to main content
15,896,912 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
I have an textbox in which i am writing product Names separated by a comma(,). I want to insert that product Names into database. But if the product Name already exist then update it otherwise
if a new product name in the textbox then i have to insert into database. how will i do it Please help . This is my code.
C#
String Serials = TextBox7.Text;
    //    String[] SerialArray = Serials.Split(',');
    //    for (int i = 0; i < SerialArray.Length - 1; i++)
    //    {
    //        con.Open();
    //        string ratecard = "Insert into Ratecard (Vendor_Name,Asset_type,New,Refurbish,Repaired) values('" + TextBox1.Text + "','" + SerialArray[i] + "',0,0,0)";
    //        SqlCommand cmdd = new SqlCommand(ratecard, con);
    //        cmdd.ExecuteNonQuery();
    //        con.Close();
Posted
Updated 1-May-14 1:41am
v2
Comments
[no name] 1-May-14 7:30am    
Your code is commented out.
You are not checking the database for your existing name.
You are using string concatenation to construct your query.
You are opening and closing your connection every time through your for loop.
Why would you need to update the name if it exists?
Member 10578683 1-May-14 7:55am    
nothing to update i just want to insert those Asset_type that is not in the db
[no name] 1-May-14 8:28am    
Okay then why did you say you needed to update the name? Did you bother going and fixing any other problems pointed out to you yet?
Sanket Saxena 1-May-14 7:34am    
Is this the code you are using to save the value in the DB. (its commented)?
Member 10578683 1-May-14 7:54am    
No no it is wrongly commented

You can make use of sp as follows:
C#
CREATE PROCEDURE [Insert_Update_Details]
(
   //parameters
)
AS
BEGIN
if exists (your query to check the existence of specified value) 
//update query 
else 
//insert query 
END
 
Share this answer
 
you can change the sql statement bit,

C#
SqlCommand cmdd = new SqlCommand("IF NOT EXISTS(SELECT 1 from Ratecard where Vendor_Name='" + TextBox1.Text + "')" +
                " Insert INTO Ratecard (Vendor_Name,Asset_type,New,Refurbish,Repaired) VALUES('" + TextBox1.Text + "','" + SerialArray[i] + "',0,0,0)"+
                " else" +
                " UPDATE Ratecard SET Asset_type ='" + SerialArray[i] + "' WHERE  Vendor_Name= '" + TextBox1.Text + "'", con);


Don't concatenate sql statement like above, it is not the best practice
your program is widely open for sql injection attacks, try to use parameterized sql
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900