check the key value before inserting data [modified]---ALREADY SOLVED---
-
let suppose i have table like this:
id name key
1 sam sam1
2 joy joy2name and key are inserted by user. Now whenever i am inserting new value, I need to check whelther I have that key exists or not. If yes, do nothing and if no, insert it. I know how to do it in dot net page but can I do this in sql query itself ? If yes, can anyone please help me..
suchita
modified on Wednesday, June 29, 2011 9:32 AM
Hello SayamiSuchi, This problem can be solved in many ways. Method 1: As has already been answered by UNCRushFan
IF NOT EXISTS (SELECT DISTINCT keyname FROM <table_name>)
BEGIN
INSERT INTO.....
ENDMethod 2: Another traditional way [ Count(ColumnName) approach ]
Declare @tblSource table([ID] int identity,[Name] varchar(20),[Key] varchar(10))
insert into @tblSource Select 'Sam', 'Sam1' Union all Select 'Joy','Joy2'
--Select * from @tblSourceDeclare @key as varchar(10)
set @key = 'Joy2'if(( Select count([KEY]) from @tblSource where [key] = @key) = 1)
begin
insert into @tblSource Select 'NewName', 'NewKey'
endSelect * from @tblSource
Method 3: Merge statement of Sql Server 2008 Consider the below statement first
Declare @tblSource table([ID] int identity,[Name] varchar(20),[Key] varchar(10))
insert into @tblSource Select 'Sam', 'Sam1' Union all Select 'Joy','Joy2'Declare @tblDestination table([ID] int identity,[Name] varchar(20),[Key] varchar(10))
MERGE INTO @tblDestination AS Target
USING (SELECT [Name],[Key] FROM @tblSource) AS Source
ON Target.[Key] = Source.[Key]
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, [Key]) VALUES (Source.Name, Source.[Key]);Select * from @tblDestination
I have a source table and a destination table. I am inserting the record in the destination table by checking whether the Key of the source table exists in the destination or not. In this case no key will be found in the destination and hence the output will be
ID Name Key
1 Sam Sam1
2 Joy Joy2Now let us insert a record (with an already existing key) in the source table as
insert into @tblSource Select 'Joy','Joy2'
At this time the records in the source table will be
ID Name Key
1 Sam Sam1
2 Joy Joy2
3 Joy Joy2Now if we run the above Merge statement query
MERGE INTO @tblDestination AS Target
USING (SELECT [Name],[Key] FROM @tblSource) AS Source
ON Target.[Key] = Source.[Key]
WHEN NOT MATCHED BY TARGET THEN
INSERT (Name, [Key]) VALUES (Source.Name, Source.[Key]);
Select * from @tblDestinationThe output in the destination table will be
ID Name Key
1 Sam Sam1
2 Joy Joy2because the key is already present in the destination table and hence it has been ignored. But if we have the source table as
insert into @tblSource Select 'NewName',