Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Insert question??

Author  Topic 

raaj
Posting Yak Master

129 Posts

Posted - 2009-05-05 : 19:56:05
Hi Guys,
I want a simple code for this scenario :

we need to insert a recored in one table
if that record already there in that table then it must not insert in that table
Here is the sample data :

declare @Mytable2 table
(authors_name varchar(100))

insert into @Mytable2 select 'Mathew Arnold'
insert into @Mytable2 select 'Keith Davis'
insert into @Mytable2 select 'David Taylor'
insert into @Mytable2 select 'Agatha Christy'
insert into @Mytable2 select 'Sidney Sheldon'
insert into @Mytable2 select 'Mcarthur'
insert into @Mytable2 select 'David Taylor'

--select * from @Mytable2

As you can see, David Taylor name is twice.....so I do not want it to be inserted as it already there previously......



Any ideas???
Thanks.......

Tapalotapus
Starting Member

22 Posts

Posted - 2009-05-05 : 20:10:42

declare @MyValues table (val varchar(100))

insert into @MyValues select 'Mathew Arnold'
insert into @MyValues select 'Keith Davis'
insert into @MyValues select 'David Taylor'
insert into @MyValues select 'Agatha Christy'
insert into @MyValues select 'Sidney Sheldon'
insert into @MyValues select 'Mcarthur'
insert into @MyValues select 'David Taylor'

--select * from @MyValues

declare @Mytable2 table
(authors_name varchar(100))

INSERT INTO @Mytable2(authors_name)
SELECT DISTINCT val
FROM @Myvalues
LEFT JOIN @Mytable2
ON val = authors_name
WHERE authors_name IS NULL

select * from @Mytable2
Go to Top of Page
   

- Advertisement -