T-SQL提供了幾種數據插入的語句:INSERT VALUES、INSERT SELECT、INSERT EXEC、SELECT INTO及BULK INSERT。spa
INSERT VALUES語句:code
INSERT INTO dbo.Orders(orderid, orderdate, empid, custid) VALUES(10001, '20090212', 3, 'A');
SQL Server 2008加強了VALUES語句的功能,容許在一條語句中指定由逗號分隔開的多行記錄:blog
INSERT INTO dbo.Orders (orderid, orderdate, empid, custid) VALUES (10003, '20090213', 4, 'B'), (10004, '20090214', 1, 'A'), (10005, '20090213', 1, 'C'), (10006, '20090215', 3, 'C');
在SQL Server 2008中還能夠用VALUES來構建虛擬表:索引
SELECT * FROM ( VALUES (10003, '20090213', 4, 'B'), (10004, '20090214', 1, 'A'), (10005, '20090213', 1, 'C'), (10006, '20090215', 3, 'C') ) AS O(orderid, orderdate, empid, custid);
INSERT SELECT語句,注意,目標表必須事先存在。ip
INSERT INTO dbo.Orders(orderid, orderdate, empid, custid) SELECT orderid, orderdate, empid, custid FROM TSQLFundamentals2008.Sales.Orders WHERE shipcountry = 'UK';
INSERT EXEC語句get
INSERT INTO dbo.Orders(orderid, orderdate, empid, custid) EXEC TSQLFundamentals2008.Sales.usp_getorders @country = 'France';
SELECT INTO語句it
SELECT orderid, orderdate, empid, custid INTO dbo.Orders FROM TSQLFundamentals2008.Sales.Orders;
SELECT INTO語句會複製來源表的基本結構(包括列名、數據類型、是否容許爲NULL及IDENTITY屬性)和數據。約束、索引及觸發器不會歷來源表中複製過來。ast
BULK INSERT語句class
BULK INSERT dbo.Orders FROM 'c:\temp\orders.txt' WITH ( DATAFILETYPE = 'char', FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' );
如下代碼將刪除具備最小訂單ID值的50個訂單,而不是隨機刪除50行:dva
WITH C AS ( SELECT TOP(50) * FROM dbo.Orders ORDER BY orderid ) DELETE FROM C;
INSERT INTO dbo.T1(datacol) OUTPUT inserted.keycol, inserted.datacol SELECT lastname FROM TSQLFundamentals2008.HR.Employees WHERE country = N'USA';
OUTPUT子句爲每一個修改過的行返回一個輸出行。若是有一個需求,出於審覈的目的,須要把修改過的行的一個子集導入一個表:
INSERT INTO dbo.ProductsAudit(productid, colname, oldval, newval) SELECT productid, N'unitprice', oldval, newval FROM (UPDATE dbo.Products SET unitprice *= 1.15 OUTPUT inserted.productid, deleted.unitprice AS oldval, inserted.unitprice AS newval WHERE SupplierID = 1) AS D WHERE oldval < 20.0 AND newval >= 20.0;