Use MERGE statement SQL

Create table Mydata

CREATE TABLE [dbo].[Mydata](
[id] [int] NULL,
[name] [nchar](10) NULL
) ON [PRIMARY]

–Use MERGE statement SQL
Declare @Resultset Table (id int, name nvarchar(50) )
insert into @Resultset values(11,’aaa’)
select * from @Resultset

MERGE
[mydata].[dbo].[Mydata] AS Target
Using
(
Select id,name from @Resultset
) AS Source (id, name)
ON (
Target.Id = Source.Id and
Target.Name = Source.Name

)
WHEN NOT MATCHED THEN
INSERT (Id,Name)
VALUES (Source.Id, Source.name);

select * from [mydata].[dbo].[Mydata]

 

It the values matches from Mydata table then Merge will not insert those values into Mydata table.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s