Search code examples
sqlsql-serverwindows-server-2012

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


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' = '[email protected]'

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 ?


Solution

  • You can try the following:

    INSERT INTO dbo.table2 (UserID)
    SELECT UserID
    FROM dbo.table1
    WHERE NOT EXISTS (SELECT UserID
    FROM dbo.table2)