SQL Syntax select something from a table and insert the result into a new table if it doesn't exist

StackOverflow https://stackoverflow.com/questions/21406642

문제

I am pretty new to SQL syntax and I have the following Scenario on Windows Server using MSSQL 2012:

2 tables, lets call them table1 and table2

I now want to select a user by email from dbo.table1 and take out his UserID , later I need to insert this UserID into dbo.table2 if the table doesn't have this UserID already.

So I start doing a simple select :

Select from dbo.table1 where 'email' = 'xxx@xxx.xx'

now I need to select the UserID of that account and push it to dbo.table2 if dbo.table2 has no UserID like that.

How do I achieve that ?

도움이 되었습니까?

해결책

You can try the following:

INSERT INTO dbo.table2 (UserID)
SELECT UserID
FROM dbo.table1
WHERE NOT EXISTS (SELECT UserID
FROM dbo.table2)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top