INSERT 语句示例
(2011-04-14 21:26:09)
标签:
sqlserverinsertit |
分类: T-SQL编程 |
INSERT
例1:简单的INSERT
use tempdb
if object_id('Table_A','U') is not null begin
end
Go
create table Table_A(Column_1 int,Column_2 nchar(20),Column_3 datetime)
insert into Table_A(Column_1,Column_2,Column_3)
select * from Table_A
例2:插入值少于列个数
use tempdb
if object_id('Table_B','U') is not null begin
end
Go
create table Table_B(
,Column_2 nchar(20)
,Column_3 datetime default(getdate()))
insert into Table_B(Column_2) values(N'Agnetha Fältskog')
select * from Table_B
例3:使用SELECT插入数据
insert into Table_B(Column_2) select Column_2 from Table_A
insert into Table_B(Column_2) select N'Björn Ulvaeus'
例4:SELECT…INTO
select...into可以将查询结果的数据和结构信息保存到一个新建的表中,包括identity属性,但是无法复制约束。
use tempdb
if object_id('Table_C','U') is not null begin
end
Go
select * into Table_C from Table_B
sp_help Table_C
例5:覆盖列的IDENTITY属性
set identity_insert Table_C on
insert into Table_C(Column_1,Column_2) select 4,N'Anni Frida'
select * from Table_C
例6:使用DEFAULT VALUES
如果表中的字段都有默认值,那么可以使用default values来简化insert语句。
use tempdb
if object_id('Table_D','U') is not null begin
end
Go
create table Table_D(
,Column_2 nchar(20) default('TomSawyer')
,Column_3 datetime default(getdate()))
insert into Table_D default values
select * from Table_D
例7:使用EXECUTE插入数据
use tempdb
if object_id('Table_E','U') is not null begin
end
Go
create table Table_E(
,dbid
,ObjId
,IndId
,Type
,Resource nchar(32)
,mode
,Status
)
insert into Table_E exec sp_lock
select * from Table_E
declare @FileList table(filename nvarchar(max))
insert @FileList exec('xp_cmdshell ''dir C:\''')
select * from @FileList