2

Hello I would like to insert in a table called Data multiple columns from another table called SourceTable and one colum that has a standar value for every row added in Data.

Assume that you have Column1 and Column2 in the table called SourceTable and source_id is precalculated and it will be the same for every row added into Data on this query.

INSERT INTO Data (Columns1, Column2, source_id)
SELECT Column1, Column2
FROM SourceTable
UNION SELECT 2;

I tried this one but is not working, most likely because the SELECT 2 returns only one row.

1
  • select 2 from foo will select a hardcoded 2 for every record in the table. you're not limited to selecting just fields/function values.
    – Marc B
    Jun 7, 2016 at 15:38

1 Answer 1

6

Your issue is that you're giving SQL 3 columns to insert 2 values into, if source_id is going to be 2 as your union selects then you'd want something like this;

INSERT INTO Data (Columns1, Column2, source_id)
SELECT Column1, Column2, 2
FROM SourceTable

The number of columns you're inserting needs to match the number of columns that you're inserting to. The way you were doing it would have produced this result;

Column1   Column2   source_id
Value1    Value2
2

but even the union would have failed as the queries that you're unioning need to have the same number of columns.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.