Click here to Skip to main content
15,891,567 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i need to insert into stock table a new data and if exists means update it in sql server
Posted

keep an identity column in your stock table...fro eg. stock_id
so you can insert/update as

SQL
if exists(select * from stock where stock_id = @stock_id)
Begin
     Update stock
     set (........)
     where stock_id = @stock_id
End

ELse
Begin

    insert into stock
     (....)
End
 
Share this answer
 
Comments
Sharon 2 20-May-13 1:15am    
for first insert how can i give the value of @stock_id from front end as parameter value
Sunny_Kumar_ 20-May-13 1:20am    
what primary key column you have in your stock table?
Sharon 2 20-May-13 1:21am    
stock-id itself
Sunny_Kumar_ 20-May-13 1:36am    
then you must have some constraint to distinguish the uniqueness of data at a given level in order to achieve this purpose, otherwise I'm afraid you can do this. As far I can see, this stock_id PK gives you the power to read unique rows only not the unique data.
Sharon 2 20-May-13 1:37am    
i have purid means id that come from purchase table,can you please show an example with this type stock_id
if you want to check whether the product exists or not before you update it then you can use sqlDataAdapter.
C#
DataTable dt = new DataTable();
string check = "SELECT * FROM TABLENAME WHERE product = '"+textBox1.Text+"';
sqlcommand cmd = new sqlcommand("check");
sqlDataAdapter adap = new sqlDataAdapter("cmd", yourdatabaseconnection);
try
{
adap.Fill(dt)
}
catch(exception ex)
{
throw ex;
}
if(dt.Rows.Count>0)
{
//here goes your code for update
}
else
{
// here goes code for new insertion 
}


I have demonstrated using concat. Its best idea to use Stored Procedure. Plz use stored procedure while implementing..
Hope i met ur requirement!
 
Share this answer
 
Comments
Sharon 2 20-May-13 4:50am    
thanks to all i got it..

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