如何在SQL中从一个表插入另一个具有额外值的表?

时间:2014-12-13 22:28:52

标签: sql sql-server tsql sql-insert

我有两张桌子。我想从Table1插入到Table2中,我想在表2中的列中插入额外的值。有没有办法在一个SQL语句中完成所有这些?

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, 

这是我的SQL语句:

INSERT INTO Table2 ([Id], [Item Description], [Item Cost])
SELECT NEWID(), Description, Cost FROM  Table1
WHERE Id = '1'

2 个答案:

答案 0 :(得分:7)

只需将值与列表中的列一起添加到select行:

INSERT INTO Table2 ([Id], [Item Description], [Item Cost], [Order Date])
    SELECT NEWID(), Description, Cost, '2014-12-13'
    FROM  Table1
    WHERE Id = '1';

答案 1 :(得分:1)

您可以通过在select statement

中添加特定列的值来实现

喜欢,

INSERT INTO TABLE2([COL1], [COL2], [COL3], [COL4])
    SELECT [COL1], [COL2], 'Value1', 'Value2'
    FROM TABLE1

表格的SQL语句

INSERT INTO TABLE2 ([Id], [Item Description], [Item Cost], [Order Number], [Order Date] )
    SELECT NEWID(), Description, Cost, '1234', '2012-12-12' 
    FROM  TABLE1
    WHERE Id = '1'