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