Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to check the existing data in database with the inserting data....
Posted

If you mean that you want to insert data if it is new, and update it is it already exists, then your best option is probably to write a stored procedure to do it.
The exact procedure will depend on your table and what makes a row "exist", but there is an example here: http://forums.asp.net/t/1608207.aspx/1[^]
 
Share this answer
 
Comments
akrati shakya 11-Apr-13 5:05am    
but i am not using procedure becoz table name has to be retrieved from database.... if it is possible then how to write procedure... plz give example...
Hi
You must use from bellow Stored Procedure for do this:

SQL
Create	Procedure	YourStoredProcedureName
@ID		Bigint		
-- and add another parameter here
As
	Begin Try
		Update	YourTableName
			Set	All parameters without ID must be set

			Where	ID	= @ID	

		IF	@@ROWCOUNT	=	0
		Begin
			Insert	YourTableName(All parameters without ID)
				Values(All parameters without ID)
		End
		Select	0
		Return	

	End	Try
	Begin	Catch
		Select	Error_Number() * -1
		Return	
	End	Catch


I hope it is helpful for you.
 
Share this answer
 
v2
Comments
akrati shakya 11-Apr-13 5:09am    
but i am not using procedure becoz table name has to be retrieved from database.... if it is possible then how to write procedure... plz give example...
Reza Alipour Fard 12-Apr-13 6:09am    
If your table name has in your DB, you must be create your script in your application and execute it.
for doing this action you must be replace your table name instead of YourTableName after that execute Try and Catch parts.
First off all your question is not clear as per my understanding , you want inserting the data if the record is not exist....


SQL
IF NOT EXISTS ( SELECT COL1 FROM TABLE WHERE PK_COL1=@COL1)
BEGIN
   -- INSERT QUERY
END
 
Share this answer
 
Do you want to Protect your database from Duplicate id......
SQL
Insert into Table(All parameters with ID)
                Values(All parameters with ID) where Id<>CurrentVal Which you want to insert as Id
 
Share this answer
 
Just use a simple "if Exist" of sql command for the data that are you trying to insert, before inserting data.
 
Share this answer
 
If you are using SQL Server 2008 (or above) then you can use MERGE.

http://technet.microsoft.com/en-us/library/bb510625.aspx[^]
 
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