如何从select语句向表中添加插入

时间:2015-09-02 19:19:42

标签: sql sql-server

我想从一个表中插入数据,从另一个表中选择数据。例如,我这样做:

INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;

例如,

select语句将返回,并插入:

Robert    USA
Richard   Germany
Pat       USA

这很好用。

我现在要做的是填充一个不属于供应商表的日期转移列。日期将是今天(getdate)

insert语句为:

insert into Customer(CustomerName, Country, datetransfered)

如何为select语句中返回的每一行添加'datetransfered'部分作为“今天的日期”(GetDate)?

我想插入:

Robert    USA         9/2/15
Richard   Germany     9/2/15
Pat       USA         9/2/15

2 个答案:

答案 0 :(得分:3)

只需添加getdate()并将其转换为select语句中的日期,如下所示:

INSERT INTO Customers (CustomerName, Country,datetransfered)
SELECT SupplierName, Country,cast(getdate() as date) FROM Suppliers;

<强>结果:

+--------------+---------+----------------+
| CustomerName | Country | datetransfered |
+--------------+---------+----------------+
| Robert       | USA     | 2015-09-02     |
| Richard      | Germany | 2015-09-02     |
| Pat          | USA     | 2015-09-02     |
+--------------+---------+----------------+

SQL Server Demo

答案 1 :(得分:2)

试试这个:

INSERT INTO Customers (CustomerName, Country, datetransfered)
SELECT SupplierName, Country, getdate() FROM Suppliers;

getdate()会在您的datetransfered列中插入今天的日期。

修改

如果您只想存储日期部分,则需要将其转换为getdate(),返回类型为日期时间

INSERT INTO Customers (CustomerName, Country, datetransfered)
SELECT SupplierName, Country, cast(getdate() as date) FROM Suppliers

或使用Convert()

INSERT INTO Customers (CustomerName, Country, datetransfered)
SELECT SupplierName, Country, CONVERT(DATE, GETDATE()) FROM Suppliers