Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert from one table into another with extra values in SQL?

I have two tables. I want to insert from Table1 into Table2, and I would like to insert extra values into the columns that Table 2 has. Is there a way to do this all in one SQL statement?

Table 1

[Id]             UNIQUEIDENTIFIER NOT NULL,
[Description]    VARCHAR (140)    NULL,
[Cost]           MONEY            NULL,

Table 2

[Id]                  UNIQUEIDENTIFIER NOT NULL,
[Order Number]        NVARCHAR (10)    NULL,
[Order Date]          DATETIME         NULL,
[Item Number]         NVARCHAR (4)     NULL,
[Item Description]    VARCHAR (140)    NULL,
[Item Cost]           MONEY            NULL,
[Order Total Cost]    MONEY            NULL,
[Order Tax Cost]      MONEY            NULL, 

Here is my SQL Statement:

INSERT INTO Table2 ([Id], [Item Description], [Item Cost])
SELECT NEWID(), Description, Cost FROM  Table1
WHERE Id = '1'
like image 213
nate Avatar asked Dec 19 '22 08:12

nate


1 Answers

Just add the values onto the select line along with the columns in the column list:

INSERT INTO Table2 ([Id], [Item Description], [Item Cost], [Order Date])
    SELECT NEWID(), Description, Cost, '2014-12-13'
    FROM  Table1
    WHERE Id = '1';
like image 98
Gordon Linoff Avatar answered Dec 28 '22 08:12

Gordon Linoff