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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 insert into where record does not exist

Author  Topic 

tech
Starting Member

32 Posts

Posted - 2012-05-30 : 19:44:47
I have 2 tables:

users
userattributes

I wish to insert data into userattributes where the userID in does not exist from the users table into the userattributes table.

how would I do this?

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2012-05-30 : 21:07:23
[code]
INSERT INTO userattributes ( userID, . . . )
SELECT u.userID, . . .
FROM users u
WHERE NOT EXISTS (SELECT * FROM userattributes a WHERE a.userID = u.userID)
[/code]


KH
[spoiler]Time is always against us[/spoiler]

Go to Top of Page

SQL Basic
Starting Member

8 Posts

Posted - 2012-05-31 : 06:02:39
Also, you can modify with this code below :

INSERT INTO table2 (file_index, celeb_name)
SELECT file_index, 'userID'
FROM table1
WHERE filename = 'user'
AND file_index NOT IN (SELECT DISTINCT file_index
FROM table2
WHERE user_name = 'userID')
Go to Top of Page
   

- Advertisement -