加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

INSERT 语句示例

(2011-04-14 21:26:09)
标签:

sql

server

insert

it

分类: T-SQL编程

INSERT

 

 

1:简单的INSERT

 

use tempdb

if object_id('Table_A','U') is not null begin

   drop table Table_A

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)

   values(1,N'Benny Andersson',getdate())

select * from Table_A

 

2:插入值少于列个数

 

use tempdb

if object_id('Table_B','U') is not null begin

   drop table Table_B

end

Go

create table Table_B(

 Column_1 int identity

,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'

 

4SELECT…INTO

 

select...into可以将查询结果的数据和结构信息保存到一个新建的表中,包括identity属性,但是无法复制约束。

 

use tempdb

if object_id('Table_C','U') is not null begin

   drop table Table_C

end

Go

 

select * into Table_C from Table_B

 

sp_help Table_C

 

5:覆盖列的IDENTITY属性

 

    当表的identity_insert属性被设置为on时,就可以将显式值插入到标识列。

 

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

   drop table Table_D

end

Go

create table Table_D(

 Column_1 int identity

,Column_2 nchar(20) default('TomSawyer')

,Column_3 datetime default(getdate()))

 

insert into Table_D default values

select * from Table_D

 

7:使用EXECUTE插入数据

 

    INSERT…EXECUTE可以将存储过程返回的结果保存在表中。

 

use tempdb

if object_id('Table_E','U') is not null begin

   drop table Table_E

end

Go

create table Table_E(

 spid     smallint

,dbid     smallint

,ObjId    int

,IndId    smallint

,Type     nchar(4)

,Resource nchar(32)

,mode     nvarchar(8)

,Status   nvarchar(5)

)

insert into Table_E exec sp_lock

 

select * from Table_E

 

 

    SQL Server 2005中,推荐使用动态管理视图来获取系统信息,其中一个优势就是:根据需要筛选所需的字段,而存储过程返回的行集结构是固定的。这里也可以使用查询字符串来代替存储过程:

 

declare @FileList table(filename nvarchar(max))

insert @FileList exec('xp_cmdshell ''dir C:\''')

select * from @FileList

 

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有