SQL Server : is there a way to insert into a table values using both SELECT and VALUES at the same time?

insert, select, sql, sql-server

Solution

The `INSERT` command comes in two flavors:

(1) either you have all your values available, as literals or SQL Server variables - in that case, you can use the `INSERT .. VALUES()` approach:

INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
VALUES(Value1, Value2, @Variable3, @Variable4, ...., ValueN)

Note: I would recommend to always explicitly specify the list of column to insert data into - that way, you won't have any nasty surprises if suddenly your table has an extra column, or if your tables has an `IDENTITY` or computed column. Yes - it's a tiny bit more work - once - but then you have your `INSERT` statement as solid as it can be and you won't have to constantly fiddle around with it if your table changes.

(2) if you don't have all your values as literals and/or variables, but instead you want to rely on another table, multiple tables, or views, to provide the values, then you can use the `INSERT ... SELECT ...` approach:

INSERT INTO dbo.YourTable(Col1, Col2, ...., ColN)
   SELECT
       SourceColumn1, SourceColumn2, @Variable3, @Variable4, ...., SourceColumnN
   FROM
       dbo.YourProvidingTableOrView

Here, you must define exactly as many items in the `SELECT` as your `INSERT` expects - and those can be columns from the table(s) (or view(s)), or those can be literals or variables. Again: explicitly provide the list of columns to insert into - see above.

You can use one or the other - but you cannot mix the two - you cannot use `SELECT` and have a `VALUES(...)` clause in the middle of it - pick one of the two - stick with it.

So in your concrete case, just use:

INSERT INTO dbo.table_name (ID, Name, Email) 
  SELECT userID, userName, 'example@yahoo.com'
  FROM users_table 
  WHERE condition1 

Problem

I'm trying to set up a trigger that will insert certain values from a table and specify other values with the `VALUES` command. Something like the code below: ``` INSERT INTO table_name(ID, Name, Email) SELECT userID, userName FROM users_table WHERE condition1 VALUES ('example@yahoo.com') ``` So as you can see, I'm trying to fetch first 2 values for `ID` and `Name` from a table and for `email` I want to specify a value. Also I have an auto-increment column (called `crt`) in `table_name` if that is relevant. So how can I do this?

Original source