Sql-server – Insert query with a subquery

insertsql serversubquery

I want to insert somewhere around 400 rows into a table. All of the column values will be the same fixed value for most of the columns, with exception to one column which I want to pull from a fairly complicated subquery that will pull over 400 unique values from another table using a series of joins and where statements. We attempted the following query:

INSERT INTO mytable (col1, col2, col3, col4)
VALUES(val1, (subquery), val2, val3)

It stated, that it wouldn't work because the subquery yielded more than one result. The only values being pulled from a different table is in the subquery. I cannot insert the subquery into the respective column by itself, since col1 is a NOT NULL column.

Best Answer

If the (subquery) has SELECT (whatever expression) AS col FROM ..., then you can do:

INSERT INTO mytable 
  (col1, col2, col3, col4) 
SELECT 
  val1, s.col, val2, val3
FROM 
  (subquery) AS s ;

or:

WITH s (col) AS
  (subquery)
INSERT INTO mytable 
  (col1, col2, col3, col4) 
SELECT 
  val1, s.col, val2, val3
FROM 
  s ;