您好,欢迎访问一九零五行业门户网

sql insert select语句的使用方法

sql insert 语句的使用方法
insert 语句中的 select 子查询可用于将一个或多个其它的表或视图的值添加到表中。使用 select 子查询可同时插入多行。
下面的 insert 语句将 titles 中数据的 type 是 modern cooking 的所有行的数据插入到一个单独的表中:
use pubsinsert into mybooks   select title_id, title, type   from titles   where type = 'mod_cook'子查询的选择列表必须与 insert 语句列的列表匹配。如果没有指定列的列表,选择列表必须与正向其插入的表或视图的列匹配。
insert...select 语句的另一个作用是从 microsoft® sql server™ 的外部数据源插入数据。insert 语句中的 select 可以:
使用由四部分组成的名称引用链接服务器上的远程表。有关更多信息,请参见使用链接服务器名标识数据源。
使用 openrowset 引用远程表。有关更多信息,请参见使用特殊名称标识数据源。
7> create table customers (
8>      customerid nchar (5) not null ,
9>      companyname nvarchar (40) not null ,
10>     contactname nvarchar (30) null ,
11>     contacttitle nvarchar (30) null ,
12>     address nvarchar (60) null ,
13>     city nvarchar (15) null ,
14>     region nvarchar (15) null ,
15>     postalcode nvarchar (10) null ,
16>     country nvarchar (15) null ,
17>     phone nvarchar (24) null ,
18>     fax nvarchar (24) null
19> )
20> go
1>
2>
3> insert into customers (customerid, companyname) select '1', 'bam bam'
4> go
(1 rows affected)
1>
2> select * from customers;
3> go
customerid companyname                              contactname                    contacttitle                   address                                                      city            region
       postalcode country         phone                    fax
---------- ---------------------------------------- ------------------------------ ------------------------------ ------------------------------------------------------------ --------------- ---------
------ ---------- --------------- ------------------------ ------------------------
1          bam bam                                  null                           null                           null                                                         null            null
       null       null            null                     null
(1 rows affected)
1>
2> drop table customers;
3> go
实例
3> insert into billingarchive
4>     (bankerid, billingnumber, billingtotal, credittotal,
5>     paymenttotal, termsid, billingdate, billingduedate)
6> select
7>     bankerid, billingnumber, billingtotal, credittotal,
8>     paymenttotal, termsid, billingdate, billingduedate
9> from billings
10> where billingtotal - paymenttotal - credittotal = 0
11> go
也可以利用存储过程处理
3> create procedure spins_employee
4> @firstname    nvarchar(50),
5> @lastname  nvarchar(25),
6> @salary   money
7> as
8> insert into employee (id, first_name, last_name, salary)
9> select 10, @firstname, @lastname, @salary
10> go
1> spins_employee 'gadget', 'bond', 49.95
2> go
其它类似信息

推荐信息