Click here to Skip to main content
15,881,856 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I need some help with asp.net, ado.net & sql
I have 2 sql tables. One stores the book information and other table stores the number of copies. what i want is, I want to first check if the book of same name is already present and if book is already present then it should increment the values in copy column of copies table.
for example, first table contains books information with columns like its name,publisher,edition and second table has name and number of copies. so when I add any book information, then it should check booktable based on book name and if same book is present then it should increment value in copies table. this is what i have written but its not working
SqlConnection additemconn = new SqlConnection(strconn);
            additemconn.Open();
            SqlCommand checkcomm = new SqlCommand("if EXISTS(select Bname from Books where Bname='" + txtItemname.Text + "') Update Bookcopies set BooksCopies=BooksCopies + 1 where Bname='" + txtItemname.Text + "' End if");
            checkcomm.Connection = additemconn;
            checkcomm.ExecuteNonQuery();
            
            
            SqlConnection additemconnadd = new SqlConnection(strconn);
            additemconn.Open();
            SqlCommand additemcomm = new SqlCommand("Insert into Books values ('" + txtItemname.Text + "','" + txtitemauthor.Text + "','" + lstitemflagged.Text + "','" + txtitempublisher.Text + "','" + txtitemedition.Text + "','" + txtitemdate.Text + "','" + txtItemId.Text + "') ");
            
            additemcomm.Connection = additemconnadd;
            additemcomm.ExecuteNonQuery();
Posted

For your question perhaps you want some sql like

IF EXISTS(select Bname from Books where Bname='NEWBOOKNAME') BEGIN
  Update Bookcopies set BooksCopies=BooksCopies + 1 where Bname='NEWBOOKNAME'
END ELSE BEGIN
 Insert into Books .....
End

in one SQL.

May be you can write a stored procedure instead. and use parameters to avoid injection.
 
Share this answer
 
Your code will work good if you take off the terminating if in your if..else query block. There is no End If in sql..its only an End
 
Share this answer
 
Firstly, use the storedproc rather than inline queries. Secondly, remove the End If
 
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