阅读目录

一、SQL分类

DDL—数据定义语言(CREATE,ALTERAV4,DROP,DECLARE)

DML—数据垄断语言(SELECT,DELETE,UPDATE,INSERT)

DCL—数据调整语言(GRANT,REVOKE,COMMIT,ROLLBACK)

 

  • 一、SQL分类
  • 二、功底语句
  • 三、sql技巧
  • 四、(MS SQL
    Server卡塔尔SQL语句导入导出大全

二、根基语句

回来目录

2.1、说明:创立数据库

create database db-name

一、SQL分类

DDL—数据定义语言(CREATE,ALTE本田CR-V,DROP,DECLARE)

DML—数据操纵语言(SELECT,DELETE,UPDATE,INSERT)

DCL—数据调整语言(GRANT,REVOKE,COMMIT,ROLLBACK)

 

再次回到目录

2.2、表达:删除数据库

drop database db-name 

二、功底语句

2.3、说明:备份sql server

--- 创建 备份
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'
--- 开始 备份
BACKUP DATABASE pubs TO testBack

2.1、表达:创立数据库

create database db-name

2.4、表达:制造新表

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根据已有的表创建新表:
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only

2.2、表达:删除数据库

drop database db-name 

2.5、表明:删除新表

drop table tabname

2.3、说明:备份sql server

--- 创建 备份
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'
--- 开始 备份
BACKUP DATABASE pubs TO testBack

2.6、表达:增添一个列

Alter table tabname add column col type

注:列扩充后将不能够去除。DB第22中学列加上后数据类型也不能够更动,唯风流倜傥能改善的是增添varchar类型的长短。

2.7、表明:增添/删除主键

Alter table tabname add primary key(col)
Alter table tabname drop primary key(col)

2.8、表明:创设/删除索引

create [unique] index idxname on tabname(col….)
drop index idxname

注:索引是不行改造的,想校订必得删除重新建。

2.9、表明:创制/删除视图

create view viewname as select statement
drop view viewname

2.4、表明:创设新表

create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)根据已有的表创建新表:
A:create table tab_new like tab_old (使用旧表创建新表)
B:create table tab_new as select col1,col2… from tab_old definition only

2.10、表明:基本sql语句选择

查询:select * from table1 where 范围
插入:insert into table1(field1,field2) s(1,2)
删除:delete from table1 where 范围
更新:update table1 set field1=1 where 范围
查找:select * from table1 where field1 like ’%1%’ ---like的语法
排序:select * from table1 order by field1,field2 [desc]
总数:select count * as totalcount from table1
求和:select sum(field1) as sum from table1
平均:select avg(field1) as avg from table1
最大:select max(field1) as max from table1
最小:select min(field1) as min from table1

2.5、表明:删除新表

drop table tabname

2.11、表明:高档查询运算

A: UNION
运算符

UNION
运算符通过结合其余多个结实表(譬如 TABLE1 和
TABLE2卡塔尔并消去表中别的重复行而派生出叁个结出表。

当 ALL 随
UNION 一齐利用时(即 UNION ALL卡塔尔国,不消亡重复行。

二种状态下,派生表的每风姿浪漫行不是出自
TABLE1 正是发源 TABLE2。

B:
EXCEPT 运算符

EXCEPT
运算符通过包涵全部在 TABLE1 中但不在 TABLE第22中学的行并撤消全部重复行而派生出三个结出表。

当 ALL 随
EXCEPT 一同使用时 (EXCEPT ALL),不拔除重复行。

C:
INTERSECT 运算符

INTETucsonSECT
运算符通过只囊括 TABLE1 和 TABLE2中都局地行并消释全体重复行而派生出三个结果表。

当 ALL 随
INTE帕JeroSECT 一同行使时 (INTE安德拉SECT ALL),不拔除重复行。

注:使用运算词的多少个查询结果行必得是生龙活虎律的。

2.6、表达:扩展四个列

Alter table tabname add column col type

注:列扩充后将不能够去除。DB第22中学列加上后数据类型也无法改换,唯大器晚成能改良的是充实varchar类型的长度。

2.7、表达:加多/删除主键

Alter table tabname add primary key(col)
Alter table tabname drop primary key(col)

2.8、表达:成立/删除索引

create [unique] index idxname on tabname(col….)
drop index idxname

注:索引是不足改换的,想纠正必得删除重新建。

2.9、表达:创设/删除视图

create view viewname as select statement
drop view viewname

2.12、表明:使用外接连

A、left
outer join:
左外连接(左连接卡塔尔国:结果集几席卷连接表的相称行,也席卷左连接表的具备行。

SQL: select
a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

B:right
outer join:
右外接连(右连接):结果集既包涵连接表的匹配连接行,也囊括右连接表的全部行。

C:full
outer join:
全外连接:不止囊括符号连接表的相称行,还包括五个接二连三表中的全数记录。

 

2.10、表达:基本sql语句选用

www.qy186.com 1

查询:select * from table1 where 范围
插入:insert into table1(field1,field2) s(1,2)
删除:delete from table1 where 范围
更新:update table1 set field1=1 where 范围
查找:select * from table1 where field1 like ’%1%’ ---like的语法
排序:select * from table1 order by field1,field2 [desc]
总数:select count * as totalcount from table1
求和:select sum(field1) as sum from table1
平均:select avg(field1) as avg from table1
最大:select max(field1) as max from table1
最小:select min(field1) as min from table1

www.qy186.com 2

补充:

1)、说明:复制表(只复制结构,源表名:a
新表名:b) (Access可用)

法一:select * into b from a where 1<>1

法二:select top 0 * into b from a

2)、说明:拷贝表(拷贝数据,源表名:a
指标表名:b) (Access可用)

insert into b(a, b, c) select d,e,f from b; 

3)、表达:跨数据库之间表的正片(具体多少利用相对路线)
(Access可用)

insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件

例子:..from b in '"&Server.MapPath(".")&"data.mdb" &"' where..

4)、说明:子查询(表名1:a
表名2:b)

select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3) 

5)、表明:显示小说、提交人和尾声回复时间

select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

6)、表达:外接连查询(表名1:a
表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 

7)、表达:在线视图查询(表名1:a
)

select * from (SELECT a,b,c FROM a) T where t.a > 1; 

8)、表达:between的用法,between约束查询数据范围时包含了边界值,not
between不满含

select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2

9卡塔尔国、表明:in
的运用形式

select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’) 

10卡塔尔国、表达:两张关联表,删除主表中早就在副表中从不的新闻

delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

11卡塔 尔(英语:State of Qatar)、表明:四表联合检查难题

select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where ..... 

12卡塔尔国、表达:日程安顿提前四分钟提示

SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 

13卡塔尔国、表明:一条sql
语句化解数据库分页

select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

14)、说明:前10条记录

select top 10 * form table1 where 范围 

15卡塔 尔(英语:State of Qatar)、表达:选用在每大器晚成组b值雷同的多寡中对应的a最大的记录的装有新闻(形似这样的用法能够用于论坛每月排行的榜单,每月抢手成品深入分析,按学科成绩排行,等等.)

select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 

16卡塔 尔(英语:State of Qatar)、表达:富含富有在
TableA 中但不在 TableB和TableC
中的行并消释全体重复行而派生出三个结实表

(select a from tableA ) except (select a from tableB) except (select a from tableC) 

17卡塔尔国、表达:随机抽出10条数据

select top 10 * from tablename order by newid() 

18卡塔 尔(阿拉伯语:قطر‎、表达:随机筛选记录

select newid()

19卡塔尔、表达:删除重复记录

Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) 

20卡塔尔国、表达:列出数据Curry全体的表名

select name from sysobjects where type='U'

21卡塔 尔(阿拉伯语:قطر‎、表达:列出表里的全部的

select name from syscolumns where id=object_id('TableName') 

22卡塔尔国、表明:列示type、vender、pcs字段,以type字段排列,case可以方便地贯彻多种选用,相仿select
中的case。

select type,
sum(case vender when 'A' then pcs else 0 end),
sum(case vender when 'C' then pcs else 0 end),
sum(case vender when 'B' then pcs else 0 end)
FROM tablename group by type

显示结果:

type vender pcs
电脑 A 1
电脑 A 1
光盘 B 2
光盘 A 2
手机 B 3
手机 C 3

23卡塔尔、表明:伊始化表table1

TRUNCATE TABLE table1 

24)、说明:选择从10到15的记录

select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

 

2.11、说明:高端查询运算

A: UNION
运算符

UNION
运算符通过结合其余八个结实表(比如 TABLE1 和
TABLE2卡塔尔并消去表中别的重复行而派生出三个结实表。

当 ALL 随
UNION 一齐利用时(即 UNION ALL卡塔尔国,不消弭重复行。

三种景况下,派生表的每风流洒脱行不是源于
TABLE1 正是源于 TABLE2。

B: EXCEPT
运算符

EXCEPT
运算符通过包罗具备在 TABLE1 中但不在 TABLE第22中学的行并消逝全部重复行而派生出一个结果表。

当 ALL 随
EXCEPT 一齐使用时 (EXCEPT ALL),不拔除重复行。

C:
INTERSECT 运算符

INTE牧马人SECT
运算符通过只囊括 TABLE1 和 TABLE2中都部分行并清除全部重复行而派生出叁个结实表。

当 ALL 随
INTE科雷傲SECT 一同使用时 (INTERubiconSECT ALL),不拔除重复行。

注:使用运算词的多少个查询结果行必得是均等的。

三、sql技巧

2.12、表达:使用外接连

A、left
outer join:
左外连接(左连接卡塔 尔(阿拉伯语:قطر‎:结果集几席卷连接表的相配行,也席卷左连接表的具备行。

SQL: select
a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

B:right
outer join:
右外接连(右连接):结果集既富含连接表的相配连接行,也囊括右连接表的有着行。

C:full
outer join:
全外连接:不独有蕴涵符号连接表的相配行,还包含三个一连表中的全体记录。

 

3.1、怎么样删除三个表中重复的笔录?

create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'

select * from a_dist

 存款和储蓄过程如下:

www.qy186.com 3www.qy186.com 4

 1 create procedure up_distinct(@t_name varchar(30),@f_key varchar(30))
 2 --f_key表示是分组字段﹐即主键字段
 3 
 4 as
 5 begin
 6 declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer
 7 select @sql = 'declare cur_rows cursor for select '+@f_key+' ,count(*) from ' +@t_name +' group by ' +@f_key +' having count(*) > 1'
 8 exec(@sql)
 9 
10 open cur_rows
11 fetch cur_rows into @id,@max
12 
13 while @@fetch_status=0
14 begin
15 select @max = @max -1
16 set rowcount @max
17 select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_key
18 if @type=56
19 select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+ @id
20 if @type=167
21 select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+''''+ @id +''''
22 exec(@sql)
23 
24 fetch cur_rows into @id,@max
25 end
26 
27 close cur_rows
28 deallocate cur_rows
29 
30 set rowcount 0
31 end
32 
33 select * from systypes
34 select * from syscolumns where id = object_id('a_dist')

View Code

补充:

1)、说明:复制表(只复制结构,源表名:a
新表名:b) (Access可用)

法一:select * into b from a where 1<>1

法二:select top 0 * into b from a

2)、说明:拷贝表(拷贝数据,源表名:a
目的表名:b) (Access可用)

insert into b(a, b, c) select d,e,f from b; 

3)、表达:跨数据库之间表的正片(具体数额利用相对路径)
(Access可用)

insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件

例子:..from b in '"&Server.MapPath(".")&"data.mdb" &"' where..

4)、说明:子查询(表名1:a
表名2:b)

select a,b,c from a where a IN (select d from b ) 或者: select a,b,c from a where a IN (1,2,3) 

5)、表明:展现散文、提交人和最后回复时间

select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b

6)、表达:外接连查询(表名1:a
表名2:b)

select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c 

7)、表明:在线视图查询(表名1:a
)

select * from (SELECT a,b,c FROM a) T where t.a > 1; 

8)、表达:between的用法,between约束查询数据范围时包罗了边界值,not
between不包蕴

select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2

9卡塔 尔(阿拉伯语:قطر‎、表达:in
的行使办法

select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’) 

10卡塔尔、表达:两张关联表,删除主表中曾在副表中尚无的消息

delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

11卡塔尔、表达:四表联合检查难点

select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where ..... 

12卡塔 尔(阿拉伯语:قطر‎、表达:日程布署提前五分钟提示

SQL: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5 

13卡塔 尔(英语:State of Qatar)、表达:一条sql
语句消除数据库分页

select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段

14)、说明:前10条记录

select top 10 * form table1 where 范围 

15卡塔 尔(英语:State of Qatar)、表达:选择在每风度翩翩组b值相符的数码中对应的a最大的笔录的持有音信(相像这样的用法能够用来论坛每月排名榜,每月抢手付加物剖析,按学科战表排行,等等.)

select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b) 

16卡塔 尔(英语:State of Qatar)、表达:包罗具有在
TableA 中但不在 TableB和TableC
中的行并淹没全体重复行而派生出叁个结出表

(select a from tableA ) except (select a from tableB) except (select a from tableC) 

17卡塔 尔(英语:State of Qatar)、表达:随机抽取10条数据

select top 10 * from tablename order by newid() 

18卡塔 尔(英语:State of Qatar)、表达:随机接受记录

select newid()

19卡塔尔国、表明:删除重复记录

Delete from tablename where id not in (select max(id) from tablename group by col1,col2,...) 

20卡塔 尔(英语:State of Qatar)、表达:列出数据库里富有的表名

select name from sysobjects where type='U'

21卡塔尔、表达:列出表里的具有的

select name from syscolumns where id=object_id('TableName') 

22卡塔 尔(阿拉伯语:قطر‎、表明:列示type、vender、pcs字段,以type字段排列,case能够一本万利地贯彻多种选拔,相同select
中的case。

select type,
sum(case vender when 'A' then pcs else 0 end),
sum(case vender when 'C' then pcs else 0 end),
sum(case vender when 'B' then pcs else 0 end)
FROM tablename group by type

浮现结果:

www.qy186.com 5

type vender pcs
电脑 A 1
电脑 A 1
光盘 B 2
光盘 A 2
手机 B 3
手机 C 3

www.qy186.com 6

23卡塔 尔(阿拉伯语:قطر‎、表明:初始化表table1

TRUNCATE TABLE table1 

24)、说明:选择从10到15的记录

select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc

 

归来目录

3.2、查询数据的最大排序难题(只好用一条语句写卡塔尔国

CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))

insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)

需求查询出来的结果如下: 

qu co je
----------- ----------- -----
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4

就是要按qu分组,每组中取je最大的前2位,且只能用一句sql语句。

select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)

三、sql技巧

3.3、求删除重复记录的sql语句

怎样把持有相近字段的笔录删除,只留下一条。

例如,表test里有id,name字段

举例有name相通的记录
只留下一条,别的的删减。

name的从头到尾的经过不定,雷同的记录数不定。

==============================

叁个风流浪漫体化的缓慢解决方案:

1)将重复的记录记入temp1表:
select [标志字段id],count(*) into temp1 from [表名]
group by [标志字段id]
having count(*)>1


2)将不重复的记录记入temp1表:
insert temp1 select [标志字段id],count(*) from [表名] group by [标志字段id] having count(*)=1

3)作一个包含所有不重复记录的表:
select * into temp2 from [表名] where 标志字段id in(select 标志字段id from temp1)

4)删除重复表:
delete [表名]

5)恢复表:
insert [表名] select * from temp2

6)删除临时表:
drop table temp1
drop table temp2

3.1、怎样删除一个表中重复的记录?

www.qy186.com 7

create table a_dist(id int,name varchar(20))

insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')
insert into a_dist values(1,'abc')

exec up_distinct 'a_dist','id'

select * from a_dist

www.qy186.com 8

 存款和储蓄进程如下:

www.qy186.com 9

www.qy186.com 10

 1 create procedure up_distinct(@t_name varchar(30),@f_key varchar(30))
 2 --f_key表示是分组字段﹐即主键字段
 3 
 4 as
 5 begin
 6 declare @max integer,@id varchar(30) ,@sql varchar(7999) ,@type integer
 7 select @sql = 'declare cur_rows cursor for select '+@f_key+' ,count(*) from ' +@t_name +' group by ' +@f_key +' having count(*) > 1'
 8 exec(@sql)
 9 
10 open cur_rows
11 fetch cur_rows into @id,@max
12 
13 while @@fetch_status=0
14 begin
15 select @max = @max -1
16 set rowcount @max
17 select @type = xtype from syscolumns where id=object_id(@t_name) and name=@f_key
18 if @type=56
19 select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+ @id
20 if @type=167
21 select @sql = 'delete from '+@t_name+' where ' + @f_key+' = '+''''+ @id +''''
22 exec(@sql)
23 
24 fetch cur_rows into @id,@max
25 end
26 
27 close cur_rows
28 deallocate cur_rows
29 
30 set rowcount 0
31 end
32 
33 select * from systypes
34 select * from syscolumns where id = object_id('a_dist')

www.qy186.com 11

3.4、行列转换–普通

假设有张学生成绩表(CJ)如下

Name Subject Result
张三  语文    80
张三  数学    90
张三  物理    85
李四  语文    85
李四  数学    92
李四  物理    82

想变成

姓名 语文 数学 物理
张三 80   90  85
李四 85   92  82

declare @sql varchar(4000)
set @sql = 'select Name'

select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a

select @sql = @sql+' from test group by name'

exec(@sql)

3.2、查询数据的最大排序难点(只好用一条语句写卡塔 尔(英语:State of Qatar)

www.qy186.com 12

CREATE TABLE hard (qu char (11) ,co char (11) ,je numeric(3, 0))

insert into hard values ('A','1',3)
insert into hard values ('A','2',4)
insert into hard values ('A','4',2)
insert into hard values ('A','6',9)
insert into hard values ('B','1',4)
insert into hard values ('B','2',5)
insert into hard values ('B','3',6)
insert into hard values ('C','3',4)
insert into hard values ('C','6',7)
insert into hard values ('C','2',3)

www.qy186.com 13

渴求查询出来的结果如下: 

www.qy186.com 14

qu co je
----------- ----------- -----
A 6 9
A 2 4
B 3 6
B 2 5
C 6 7
C 3 4

就是要按qu分组,每组中取je最大的前2位,且只能用一句sql语句。

www.qy186.com 15

select * from hard a where je in (select top 2 je from hard b where a.qu=b.qu order by je)

3.5、行列转变–合併

有表A,

id pid
1 1
1 2
1 3
2 1
2 2
3 1

如何化成表B:

id pid
1 1,2,3
2 1,2
3 1

www.qy186.com,成立二个联合的函数

create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''

select @str=@str+','+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)

return(@str)
End
go

调用自定义函数获得结果

select distinct id,dbo.fmerg(id) from 表A

 

3.3、求删除重复记录的sql语句

何以把全体同等字段的记录删除,只留下一条。

例如,表test里有id,name字段

生机勃勃经有name相近的记录
只留下一条,别的的删除。

name的内容不定,相通的记录数不定。

==============================

一个总体的解决方案:

www.qy186.com 16

1)将重复的记录记入temp1表:
select [标志字段id],count(*) into temp1 from [表名]
group by [标志字段id]
having count(*)>1


2)将不重复的记录记入temp1表:
insert temp1 select [标志字段id],count(*) from [表名] group by [标志字段id] having count(*)=1

3)作一个包含所有不重复记录的表:
select * into temp2 from [表名] where 标志字段id in(select 标志字段id from temp1)

4)删除重复表:
delete [表名]

5)恢复表:
insert [表名] select * from temp2

6)删除临时表:
drop table temp1
drop table temp2

www.qy186.com 17

3.6、如何赢得八个数据表的享有列名

先从SYSTEMOBJECT系统表中获取数据表的SYSTEMID,然后再SYSCOLUMN表中收获该数据表的有所列名。

SQL语句如下:

declare @objid int,@objname char(40)
set @objname = 'tablename'


select @objid = id from sysobjects where id = object_id(@objname)
select 'Column_name' = name from syscolumns where id = @objid order by colid

或 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='users'

 

3.4、行列转换–普通

www.qy186.com 18

假设有张学生成绩表(CJ)如下

Name Subject Result
张三  语文    80
张三  数学    90
张三  物理    85
李四  语文    85
李四  数学    92
李四  物理    82

想变成

姓名 语文 数学 物理
张三 80   90  85
李四 85   92  82

www.qy186.com 19

www.qy186.com 20

declare @sql varchar(4000)
set @sql = 'select Name'

select @sql = @sql + ',sum(case Subject when '''+Subject+''' then Result end) ['+Subject+']'
from (select distinct Subject from CJ) as a

select @sql = @sql+' from test group by name'

exec(@sql)

www.qy186.com 21

3.7、通过SQL语句来更改客商的密码

修改别人的,需要sysadmin role
EXEC sp_password NULL, 'newpassword', 'User'

如果帐号为SA执行
EXEC sp_password NULL, 'newpassword', sa

3.5、行列调换–合併

www.qy186.com 22

有表A,

id pid
1 1
1 2
1 3
2 1
2 2
3 1

如何化成表B:

id pid
1 1,2,3
2 1,2
3 1

www.qy186.com 23

创办多个统风华正茂的函数

www.qy186.com 24

create function fmerg(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str=''

select @str=@str+','+cast(pid as varchar) from 表A where id=@id
set @str=right(@str,len(@str)-1)

return(@str)
End
go

www.qy186.com 25

调用自定义函数得到结果

select distinct id,dbo.fmerg(id) from 表A

 

3.8、怎么决断出三个表的什么字段区别意为空

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE='NO' and TABLE_NAME=tablename

 

3.6、如何收获二个数据表的富有列名

先从SYSTEMOBJECT系统表中获得数据表的SYSTEMID,然后再SYSCOLUMN表中获得该数据表的装有列名。

SQL语句如下:

www.qy186.com 26

declare @objid int,@objname char(40)
set @objname = 'tablename'


select @objid = id from sysobjects where id = object_id(@objname)
select 'Column_name' = name from syscolumns where id = @objid order by colid

www.qy186.com 27

或 

SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME ='users'

 

3.9、怎样在数据Curry找到含有相近字段的表

a.
查已知列名的情事

SELECT b.name as TableName,a.name as columnname
From syscolumns a INNER JOIN sysobjects b
ON a.id=b.id
AND b.type='U'
AND a.name='字段名'

 

b.未知列名查全部在差异表出现过的列名

Select o.name As tablename,s1.name As columnname
From syscolumns s1, sysobjects o
Where s1.id = o.id
And o.type = 'U'
And Exists (
Select 1 From syscolumns s2
Where s1.name = s2.name
And s1.id <> s2.id
)

 

3.7、通过SQL语句来改造客户的密码

修改别人的,需要sysadmin role
EXEC sp_password NULL, 'newpassword', 'User'

如果帐号为SA执行
EXEC sp_password NULL, 'newpassword', sa

3.10、查询第xxx行数据

假设id是主键:

select * from (select top xxx * from yourtable) aa where not exists(select 1 from (select top xxx-1 * from yourtable) bb where aa.id=bb.id) 

要是应用游标也是能够的

fetch absolute [number] from [cursor_name]

 

注:行数为相对行数

3.8、怎么判定出三个表的怎样字段不容许为空

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where IS_NULLABLE='NO' and TABLE_NAME=tablename

 

3.11、日期总计

a. 一个月的第一天
SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)

b. 本周的星期一
SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

c. 一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

d. 季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

e. 上个月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))

f. 去年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

g. 本月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))

h. 本月的第一个星期一
select DATEADD(wk, DATEDIFF(wk,0,
dateadd(dd,6-datepart(day,getdate()),getdate())
), 0)

i. 本年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))。

 

3.9、如何在数据Curry找到含有相同字段的表

a.
查已知列名的气象

SELECT b.name as TableName,a.name as columnname
From syscolumns a INNER JOIN sysobjects b
ON a.id=b.id
AND b.type='U'
AND a.name='字段名'

 

b.未知列名查全体在不相同表现身过的列名

www.qy186.com 28

Select o.name As tablename,s1.name As columnname
From syscolumns s1, sysobjects o
Where s1.id = o.id
And o.type = 'U'
And Exists (
Select 1 From syscolumns s2
Where s1.name = s2.name
And s1.id <> s2.id
)

www.qy186.com 29

 

3.12、获取表结构[把 ‘sysobjects’ 替换 成 ‘tablename’ 即可]

SELECT CASE IsNull(I.name, '')
When '' Then ''
Else '*'
End as IsPK,
Object_Name(A.id) as t_name,
A.name as c_name,
IsNull(SubString(M.text, 1, 254), '') as pbc_init,
T.name as F_DataType,
CASE IsNull(TYPEPROPERTY(T.name, 'Scale'), '')
WHEN '' Then Cast(A.prec as varchar)
ELSE Cast(A.prec as varchar) + ',' + Cast(A.scale as varchar)
END as F_Scale,
A.isnullable as F_isNullAble
FROM Syscolumns as A
JOIN Systypes as T
ON (A.xType = T.xUserType AND A.Id = Object_id('sysobjects') )
LEFT JOIN ( SysIndexes as I
JOIN Syscolumns as A1
ON ( I.id = A1.id and A1.id = object_id('sysobjects') and (I.status & 0x800) = 0x800 AND A1.colid <= I.keycnt) )
ON ( A.id = I.id AND A.name = index_col('sysobjects', I.indid, A1.colid) )
LEFT JOIN SysComments as M
ON ( M.id = A.cdefault and ObjectProperty(A.cdefault, 'IsConstraint') = 1 )
ORDER BY A.Colid ASC

3.10、查询第xxx行数据

假设id是主键:

select * from (select top xxx * from yourtable) aa where not exists(select 1 from (select top xxx-1 * from yourtable) bb where aa.id=bb.id) 

即使采纳游标也是能够的

fetch absolute [number] from [cursor_name]

 

注:行数为相对行数

3.13、提取数据库内全数表的字段详细说明的SQL语句

SELECT
(case when a.colorder=1 then d.name else '' end) N'表名',
a.colorder N'字段序号',
a.name N'字段名',
(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else ''
end) N'标识',
(case when (SELECT count(*)
FROM sysobjects
WHERE (name in
(SELECT name
FROM sysindexes
WHERE (id = a.id) AND (indid in
(SELECT indid
FROM sysindexkeys
WHERE (id = a.id) AND (colid in
(SELECT colid
FROM syscolumns
WHERE (id = a.id) AND (name = a.name))))))) AND
(xtype = 'PK'))>0 then '√' else '' end) N'主键',
b.name N'类型',
a.length N'占用字节数',
COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'长度',
isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小数位数',
(case when a.isnullable=1 then '√'else '' end) N'允许空',
isnull(e.text,'') N'默认值',
isnull(g.[value],'') AS N'字段说明'
FROM syscolumns a
left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id=g.id AND a.colid = g.smallid
order by object_name(a.id),a.colorder

3.11、日期总括

www.qy186.com 30

a. 一个月的第一天
SELECT DATEADD(mm, DATEDIFF(mm,0,getdate()), 0)

b. 本周的星期一
SELECT DATEADD(wk, DATEDIFF(wk,0,getdate()), 0)

c. 一年的第一天
SELECT DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)

d. 季度的第一天
SELECT DATEADD(qq, DATEDIFF(qq,0,getdate()), 0)

e. 上个月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))

f. 去年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate()), 0))

g. 本月的最后一天
SELECT dateadd(ms,-3,DATEADD(mm, DATEDIFF(m,0,getdate())+1, 0))

h. 本月的第一个星期一
select DATEADD(wk, DATEDIFF(wk,0,
dateadd(dd,6-datepart(day,getdate()),getdate())
), 0)

i. 本年的最后一天
SELECT dateadd(ms,-3,DATEADD(yy, DATEDIFF(yy,0,getdate())+1, 0))。

www.qy186.com 31

 

3.14、火速获得表test的笔录总量[对大体量表特别常有效]

即刻获得表test的记录总量:

select rows from sysindexes where id = object_id('test') and indid in (0,1)

update 2 set KHXH=(ID+1)2 2行递增编号
update [23] set id1 = 'No.'+right('00000000'+id,6) where id not like 'No%' //递增
update [23] set id1= 'No.'+right('00000000'+replace(id1,'No.',''),6) //补位递增
delete from [1] where (id%2)=1


奇数
替换表名字段
update [1] set domurl = replace(domurl,'Upload/Imgswf/','Upload/Photo/') where domurl like '%Upload/Imgswf/%'

截位
SELECT LEFT(表名, 5)

截位
SELECT LEFT(表名, 5)

3.12、获取表结构[把 ‘sysobjects’ 替换 成 ‘tablename’ 即可]

www.qy186.com 32

SELECT CASE IsNull(I.name, '')
When '' Then ''
Else '*'
End as IsPK,
Object_Name(A.id) as t_name,
A.name as c_name,
IsNull(SubString(M.text, 1, 254), '') as pbc_init,
T.name as F_DataType,
CASE IsNull(TYPEPROPERTY(T.name, 'Scale'), '')
WHEN '' Then Cast(A.prec as varchar)
ELSE Cast(A.prec as varchar) + ',' + Cast(A.scale as varchar)
END as F_Scale,
A.isnullable as F_isNullAble
FROM Syscolumns as A
JOIN Systypes as T
ON (A.xType = T.xUserType AND A.Id = Object_id('sysobjects') )
LEFT JOIN ( SysIndexes as I
JOIN Syscolumns as A1
ON ( I.id = A1.id and A1.id = object_id('sysobjects') and (I.status & 0x800) = 0x800 AND A1.colid <= I.keycnt) )
ON ( A.id = I.id AND A.name = index_col('sysobjects', I.indid, A1.colid) )
LEFT JOIN SysComments as M
ON ( M.id = A.cdefault and ObjectProperty(A.cdefault, 'IsConstraint') = 1 )
ORDER BY A.Colid ASC

www.qy186.com 33

四、(MS SQL Server卡塔 尔(英语:State of Qatar)SQL语句导入导出大全

3.13、提取数据库内全体表的字段详细表达的SQL语句

www.qy186.com 34

SELECT
(case when a.colorder=1 then d.name else '' end) N'表名',
a.colorder N'字段序号',
a.name N'字段名',
(case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else ''
end) N'标识',
(case when (SELECT count(*)
FROM sysobjects
WHERE (name in
(SELECT name
FROM sysindexes
WHERE (id = a.id) AND (indid in
(SELECT indid
FROM sysindexkeys
WHERE (id = a.id) AND (colid in
(SELECT colid
FROM syscolumns
WHERE (id = a.id) AND (name = a.name))))))) AND
(xtype = 'PK'))>0 then '√' else '' end) N'主键',
b.name N'类型',
a.length N'占用字节数',
COLUMNPROPERTY(a.id,a.name,'PRECISION') as N'长度',
isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0) as N'小数位数',
(case when a.isnullable=1 then '√'else '' end) N'允许空',
isnull(e.text,'') N'默认值',
isnull(g.[value],'') AS N'字段说明'
FROM syscolumns a
left join systypes b
on a.xtype=b.xusertype
inner join sysobjects d
on a.id=d.id and d.xtype='U' and d.name<>'dtproperties'
left join syscomments e
on a.cdefault=e.id
left join sysproperties g
on a.id=g.id AND a.colid = g.smallid
order by object_name(a.id),a.colorder

www.qy186.com 35

4.1、导出到excel

EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'

 

3.14、急忙获得表test的笔录总的数量[对大体积表特别常有效]

超快拿到表test的记录总量:

www.qy186.com 36

select rows from sysindexes where id = object_id('test') and indid in (0,1)

update 2 set KHXH=(ID+1)2 2行递增编号
update [23] set id1 = 'No.'+right('00000000'+id,6) where id not like 'No%' //递增
update [23] set id1= 'No.'+right('00000000'+replace(id1,'No.',''),6) //补位递增
delete from [1] where (id%2)=1


奇数
替换表名字段
update [1] set domurl = replace(domurl,'Upload/Imgswf/','Upload/Photo/') where domurl like '%Upload/Imgswf/%'

截位
SELECT LEFT(表名, 5)

截位
SELECT LEFT(表名, 5)

www.qy186.com 37

回到目录

4.2、 导入Excel

SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

SELECT cast(cast(科目编号 as numeric(10,2)) as nvarchar(255))+' ' 转换后的别名
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 5.0;HDR=YES;DATABASE=c:Book1.xls',Sheet1$)

HDR=YES;Excel第一行当成标题行
HDR=NO;第一行不当成标题行

四、(MS SQL Server卡塔尔SQL语句导入导出大全

4.3、 导入文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" in c:DT.txt -c -Sservername -Usa -Ppassword' 

4.1、导出到excel

EXEC master..xp_cmdshell 'bcp SettleDB.dbo.shanghu out c:temp1.xls -c -q -S"GNETDATA/GNETDATA" -U"sa" -P""'

 

4.4、 导出文件文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" out c:DT.txt -c -Sservername -Usa -Ppassword'
或
EXEC master..xp_cmdshell 'bcp "Select * from dbname..tablename" queryout c:DT.txt -c -Sservername -Usa -Ppassword'

导出到TXT文本,用逗号分开
exec master..xp_cmdshell 'bcp "库名..表名" out "d:tt.txt" -c -t ,-U sa -P password'


BULK INSERT 库名..表名
FROM 'c:test.txt'
WITH (
FIELDTERMINATOR = ';',
ROWTERMINATOR = 'n'
)

 

 补充:

--/* dBase IV文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase IV;HDR=NO;IMEX=2;DATABASE=C:','select * from [客户资料4.dbf]')
--*/

--/* dBase III文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase III;HDR=NO;IMEX=2;DATABASE=C:','select * from [客户资料3.dbf]')
--*/

--/* FoxPro 数据库
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:',
'select * from [aa.DBF]')
--*/

4.2、 导入Excel

www.qy186.com 38

SELECT *
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

SELECT cast(cast(科目编号 as numeric(10,2)) as nvarchar(255))+' ' 转换后的别名
FROM OpenDataSource( 'Microsoft.Jet.OLEDB.4.0',
'Data Source="c:test.xls";User ID=Admin;Password=;Extended properties=Excel 5.0')...xactions

select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 5.0;HDR=YES;DATABASE=c:Book1.xls',Sheet1$)

HDR=YES;Excel第一行当成标题行
HDR=NO;第一行不当成标题行

www.qy186.com 39

4.5、导入DBF文件

select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;
SourceDB=e:VFP98data;
SourceType=DBF',
'select * from customer where country != "USA" order by country')
go

 

4.3、 导入文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" in c:DT.txt -c -Sservername -Usa -Ppassword' 

4.6、 导出到DBF 文件

倘诺要导出数据到曾经变化结构(即现成的)FOXPRO表中,能够一向用上面包车型客车SQL语句

insert into openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:',
'select * from [aa.DBF]')

select * from 表

 

说明:

SourceDB=c:
钦定foxpro表所在的公文夹

aa.DBF
钦点foxpro表的公文名.

 

4.4、 导出文件文件

www.qy186.com 40

EXEC master..xp_cmdshell 'bcp "dbname..tablename" out c:DT.txt -c -Sservername -Usa -Ppassword'
或
EXEC master..xp_cmdshell 'bcp "Select * from dbname..tablename" queryout c:DT.txt -c -Sservername -Usa -Ppassword'

导出到TXT文本,用逗号分开
exec master..xp_cmdshell 'bcp "库名..表名" out "d:tt.txt" -c -t ,-U sa -P password'


BULK INSERT 库名..表名
FROM 'c:test.txt'
WITH (
FIELDTERMINATOR = ';',
ROWTERMINATOR = 'n'
)

www.qy186.com 41

 

 补充:

www.qy186.com 42

--/* dBase IV文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase IV;HDR=NO;IMEX=2;DATABASE=C:','select * from [客户资料4.dbf]')
--*/

--/* dBase III文件
select * from
OPENROWSET('MICROSOFT.JET.OLEDB.4.0'
,'dBase III;HDR=NO;IMEX=2;DATABASE=C:','select * from [客户资料3.dbf]')
--*/

--/* FoxPro 数据库
select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:',
'select * from [aa.DBF]')
--*/

www.qy186.com 43

4.7、导出到Access

insert into openrowset('Microsoft.Jet.OLEDB.4.0',
'x:A.mdb';'admin';'',A表) select * from 数据库名..B表

4.5、导入DBF文件

www.qy186.com 44

select * from openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;
SourceDB=e:VFP98data;
SourceType=DBF',
'select * from customer where country != "USA" order by country')
go

www.qy186.com 45

 

4.8、导入Access

insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
'x:A.mdb';'admin';'',A表)

4.6、 导出到DBF 文件

豆蔻梢头经要导出数据到已经变化结构(即现成的)FOXPRO表中,能够直接用上边包车型客车SQL语句

insert into openrowset('MSDASQL',
'Driver=Microsoft Visual FoxPro Driver;SourceType=DBF;SourceDB=c:',
'select * from [aa.DBF]')

select * from 表

 

说明:

SourceDB=c:
钦定foxpro表所在的文件夹

aa.DBF
钦点foxpro表的公文名.

 

4.9、 导入 xml文件

 

www.qy186.com 46www.qy186.com 47

 1 DECLARE @idoc int
 2 DECLARE @doc varchar(1000)
 3 
 4 --sample XML document
 5 SET @doc ='
 6 <root>
 7 <Customer cid= "C1" name="Janine" city="Issaquah">
 8 <Order oid="O1" date="1/20/1996" amount="3.5" />
 9 <Order oid="O2" date="4/30/1997" amount="13.4">Customer was very satisfied
10 </Order>
11 </Customer>
12 <Customer cid="C2" name="Ursula" city="Oelde" >
13 <Order oid="O3" date="7/14/1999" amount="100" note="Wrap it blue
14 white red">
15 <Urgency>Important</Urgency>
16 Happy Customer.
17 </Order>
18 <Order oid="O4" date="1/20/1996" amount="10000"/>
19 </Customer>
20 </root>
21 '
22 
23 -- Create an internal representation of the XML document.
24 EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
25 
26 
27 -- Execute a SELECT statement using OPENXML rowset provider.
28 SELECT *
29 FROM OPENXML (@idoc, '/root/Customer/Order', 1)
30 WITH (oid char(5),
31 amount float,
32 comment ntext 'text()')
33 
34 EXEC sp_xml_removedocument @idoc

View Code

 

 

 

4.7、导出到Access

insert into openrowset('Microsoft.Jet.OLEDB.4.0',
'x:A.mdb';'admin';'',A表) select * from 数据库名..B表

4.10、导整个数据库

用bcp达成的存款和储蓄进程

得以完成多少导入/导出的囤积进程

依照不一致的参数,能够兑现导入/导出整个数据库/单个表

调用示例:

4.8、导入Access

insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
'x:A.mdb';'admin';'',A表)

4.10.1、导出调用示例

—-导出单个表

exec file2table 'zj','','','xzkh_sa..地区资料','c:zj.txt',1

 

—-导出全方位数据库

exec file2table 'zj','','','xzkh_sa','C:docman',1 

4.9、 导入 xml文件

 

www.qy186.com 48

www.qy186.com 49

 1 DECLARE @idoc int
 2 DECLARE @doc varchar(1000)
 3 
 4 --sample XML document
 5 SET @doc ='
 6 <root>
 7 <Customer cid= "C1" name="Janine" city="Issaquah">
 8 <Order oid="O1" date="1/20/1996" amount="3.5" />
 9 <Order oid="O2" date="4/30/1997" amount="13.4">Customer was very satisfied
10 </Order>
11 </Customer>
12 <Customer cid="C2" name="Ursula" city="Oelde" >
13 <Order oid="O3" date="7/14/1999" amount="100" note="Wrap it blue
14 white red">
15 <Urgency>Important</Urgency>
16 Happy Customer.
17 </Order>
18 <Order oid="O4" date="1/20/1996" amount="10000"/>
19 </Customer>
20 </root>
21 '
22 
23 -- Create an internal representation of the XML document.
24 EXEC sp_xml_preparedocument @idoc OUTPUT, @doc
25 
26 
27 -- Execute a SELECT statement using OPENXML rowset provider.
28 SELECT *
29 FROM OPENXML (@idoc, '/root/Customer/Order', 1)
30 WITH (oid char(5),
31 amount float,
32 comment ntext 'text()')
33 
34 EXEC sp_xml_removedocument @idoc

www.qy186.com 50

 

 

 

4.10.2、导入调用示例

—-导入单个表

exec file2table 'zj','','','xzkh_sa..地区资料','c:zj.txt',0

 

—-导入整个数据库

exec file2table 'zj','','','xzkh_sa','C:docman',0 

4.10、导整个数据库

用bcp实现的存储进度

福如东海数量导入/导出的积累进程

基于差异的参数,能够兑现导入/导出整个数据库/单个表

调用示例:

 

www.qy186.com 51www.qy186.com 52

 1 if exists(select 1 from sysobjects where name='File2Table' and objectproperty(id,'IsProcedure')=1)
 2 drop procedure File2Table
 3 go
 4 create procedure File2Table
 5 @servername varchar(200) --服务器名
 6 ,@username varchar(200) --用户名,如果用NT验证方式,则为空''
 7 ,@password varchar(200) --密码
 8 ,@tbname varchar(500) --数据库.dbo.表名,如果不指定:.dbo.表名,则导出数据库的所有用户表
 9 ,@filename varchar(1000) --导入/导出路径/文件名,如果@tbname参数指明是导出整个数据库,则这个参数是文件存放路径,文件名自动用表名.txt
10 ,@isout bit --1为导出,0为导入
11 as
12 declare @sql varchar(8000)
13 if @tbname like '%.%.%' --如果指定了表名,则直接导出单个表
14 begin
15 set @sql='bcp '+@tbname
16 +case when @isout=1 then ' out ' else ' in ' end
17 +' "'+@filename+'" /w'
18 +' /S '+@servername
19 +case when isnull(@username,'')='' then '' else ' /U '+@username end
20 +' /P '+isnull(@password,'')
21 
22 exec master..xp_cmdshell @sql
23 
24 end
25 else
26 begin --导出整个数据库,定义游标,取出所有的用户表
27 
28 declare @m_tbname varchar(250)
29 if right(@filename,1)<>'' set @filename=@filename+''
30 set @m_tbname='declare #tb cursor for select name from '+@tbname+'..sysobjects where xtype=''U'''
31 exec(@m_tbname)
32 
33 open #tb
34 
35 fetch next from #tb into @m_tbname
36 while @@fetch_status=0
37 begin
38 set @sql='bcp '+@tbname+'..'+@m_tbname
39 +case when @isout=1 then ' out ' else ' in ' end
40 +' "'+@filename+@m_tbname+'.txt " /w'
41 +' /S '+@servername
42 +case when isnull(@username,'')='' then '' else ' /U '+@username end
43 +' /P '+isnull(@password,'')
44 
45 exec master..xp_cmdshell @sql
46 
47 fetch next from #tb into @m_tbname
48 end
49 
50 close #tb
51 deallocate #tb
52 end
53 go

View Code

4.10.1、导出调用示例

—-导出单个表

exec file2table 'zj','','','xzkh_sa..地区资料','c:zj.txt',1

 

—-导出一切数据库

exec file2table 'zj','','','xzkh_sa','C:docman',1 

 

 

4.10.2、导入调用示例

—-导入单个表

exec file2table 'zj','','','xzkh_sa..地区资料','c:zj.txt',0

 

—-导入整个数据库

exec file2table 'zj','','','xzkh_sa','C:docman',0 

 

 

www.qy186.com 53

www.qy186.com 54

 1 if exists(select 1 from sysobjects where name='File2Table' and objectproperty(id,'IsProcedure')=1)
 2 drop procedure File2Table
 3 go
 4 create procedure File2Table
 5 @servername varchar(200) --服务器名
 6 ,@username varchar(200) --用户名,如果用NT验证方式,则为空''
 7 ,@password varchar(200) --密码
 8 ,@tbname varchar(500) --数据库.dbo.表名,如果不指定:.dbo.表名,则导出数据库的所有用户表
 9 ,@filename varchar(1000) --导入/导出路径/文件名,如果@tbname参数指明是导出整个数据库,则这个参数是文件存放路径,文件名自动用表名.txt
10 ,@isout bit --1为导出,0为导入
11 as
12 declare @sql varchar(8000)
13 if @tbname like '%.%.%' --如果指定了表名,则直接导出单个表
14 begin
15 set @sql='bcp '+@tbname
16 +case when @isout=1 then ' out ' else ' in ' end
17 +' "'+@filename+'" /w'
18 +' /S '+@servername
19 +case when isnull(@username,'')='' then '' else ' /U '+@username end
20 +' /P '+isnull(@password,'')
21 
22 exec master..xp_cmdshell @sql
23 
24 end
25 else
26 begin --导出整个数据库,定义游标,取出所有的用户表
27 
28 declare @m_tbname varchar(250)
29 if right(@filename,1)<>'' set @filename=@filename+''
30 set @m_tbname='declare #tb cursor for select name from '+@tbname+'..sysobjects where xtype=''U'''
31 exec(@m_tbname)
32 
33 open #tb
34 
35 fetch next from #tb into @m_tbname
36 while @@fetch_status=0
37 begin
38 set @sql='bcp '+@tbname+'..'+@m_tbname
39 +case when @isout=1 then ' out ' else ' in ' end
40 +' "'+@filename+@m_tbname+'.txt " /w'
41 +' /S '+@servername
42 +case when isnull(@username,'')='' then '' else ' /U '+@username end
43 +' /P '+isnull(@password,'')
44 
45 exec master..xp_cmdshell @sql
46 
47 fetch next from #tb into @m_tbname
48 end
49 
50 close #tb
51 deallocate #tb
52 end
53 go

www.qy186.com 55

4.11、Excel导到Txt

想用

select *
into opendatasource(…) from opendatasource(…)

金镶玉裹福禄双全将一个Excel文件内容导入到多个文件文件

 

假诺Excel中有两列,第一列为姓名,第二名列很行帐号(拾三人)

且银行帐号导出到文本文件后分两局地,前8位和后8位分别。

 

若果要用你上面的言辞插入的话,文本文件必需存在,而且有黄金年代行:姓名,银行账号1,银行账号2

接下来就能够用上面包车型客车讲话实行插队

留意文件名和目录依照你的莫过于处境张开改正.

insert into
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Text;HDR=Yes;DATABASE=C:'
)...[aa#txt]
--,aa#txt)
--*/

select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
from
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:a.xls'
--,Sheet1$)
)...[Sheet1$]

 

 

假诺你想直接插入并生成文书文件,将要用bcp

declare @sql varchar(8000),@tbname varchar(50) 

第朝气蓬勃将excel表内容导入到叁个大局临时表

select @tbname='[##temp'+cast(newid() as varchar(40))+']'
,@sql='select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
into '+@tbname+' from
opendatasource(''MICROSOFT.JET.OLEDB.4.0''
,''Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:a.xls''
)...[Sheet1$]'

exec(@sql)

下一场用bcp从大局有时表导出到文本文件

set @sql='bcp "'+@tbname+'" out "c:aa.txt" /S"(local)" /P"" /c'
exec master..xp_cmdshell @sql

剔除一时表

exec('drop table '+@tbname) 

 

 

4.12、用bcp将文件导入导出到数据库的储存进程:

bcp-二进制文件的导入导出

帮忙image,text,ntext字段的导入/导出

image相符于二进制文件;text,ntext相符于文本数据文件

 

只顾:导入时,将隐蔽满意条件的有着行

导出时,将把富有知足条件的行也出到钦定文件中

 

此存款和储蓄进度仅用bcp完结

 

/*–调用示例

–数据导出

exec p_binaryIO 'zj','','','acc_演示数据..tb','img','c:zj1.dat' 

–数据导出

exec p_binaryIO 'zj','','','acc_演示数据..tb','img','c:zj1.dat','',0

 

–*/

 

www.qy186.com 56www.qy186.com 57

 1 if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[p_binaryIO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 2 drop procedure [dbo].[p_binaryIO]
 3 GO
 4 
 5 Create proc p_binaryIO
 6 @servename varchar (30),--服务器名称
 7 @username varchar (30), --用户名
 8 @password varchar (30), --密码
 9 @tbname varchar (500), --数据库..表名
10 @fdname varchar (30), --字段名
11 @fname varchar (1000), --目录+文件名,处理过程中要使用/覆盖:@filename+.bak
12 @tj varchar (1000)='', --处理条件.对于数据导入,如果条件中包含@fdname,请指定表名前缀
13 @isout bit=1 --1导出((默认),0导入
14 AS
15 declare @fname_in varchar(1000) --bcp处理应答文件名
16 ,@fsize varchar(20) --要处理的文件的大小
17 ,@m_tbname varchar(50) --临时表名
18 ,@sql varchar(8000)
19 
20 --则取得导入文件的大小
21 
22 if @isout=1
23 set @fsize='0'
24 else
25 begin
26 create table #tb(可选名 varchar(20),大小 int
27 ,创建日期 varchar(10),创建时间 varchar(20)
28 ,上次写操作日期 varchar(10),上次写操作时间 varchar(20)
29 ,上次访问日期 varchar(10),上次访问时间 varchar(20),特性 int)
30 
31 insert into #tb
32 exec master..xp_getfiledetails @fname
33 
34 select @fsize=大小 from #tb
35 drop table #tb
36 
37 if @fsize is null
38 begin
39 print '文件未找到'
40 return
41 end
42 end

View Code

 

 扭转数据处理答复文件

set @m_tbname='[##temp'+cast(newid() as varchar(40))+']'
set @sql='select * into '+@m_tbname+' from(
select null as 类型
union all select 0 as 前缀
union all select '+@fsize+' as 长度
union all select null as 结束
union all select null as 格式
) a'

exec(@sql)

select @fname_in=@fname+'_temp'
,@sql='bcp "'+@m_tbname+'" out "'+@fname_in
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')+'" /c'

exec master..xp_cmdshell @sql

 

剔除有的时候表

set @sql='drop table '+@m_tbname
exec(@sql)

if @isout=1
begin
set @sql='bcp "select top 1 '+@fdname+' from '
+@tbname+case isnull(@tj,'') when '' then ''
else ' where '+@tj end
+'" queryout "'+@fname
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')
+'" /i"'+@fname_in+'"'


exec master..xp_cmdshell @sql
end
else
begin

 

为多少导入希图有的时候表

set @sql='select top 0 '+@fdname+' into '
+@m_tbname+' from ' +@tbname

exec(@sql)

将数据导入到不经常表

set @sql='bcp "'+@m_tbname+'" in "'+@fname
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')
+'" /i"'+@fname_in+'"'

exec master..xp_cmdshell @sql

 

 将数据导入到正式表中

set @sql='update '+@tbname
+' set '+@fdname+'=b.'+@fdname
+' from '+@tbname+' a,'
+@m_tbname+' b'
+case isnull(@tj,'') when '' then ''
else ' where '+@tj end

exec(@sql)

剔除数据管理有的时候表

set @sql='drop table '+@m_tbname
end

删除数据管理回复文件

set @sql='del '+@fname_in

exec master..xp_cmdshell @sql
go

 

 导入文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" in c:DT.txt -c -Sservername -Usa -Ppassword'

改为如下,不需引号

EXEC master..xp_cmdshell 'bcp dbname..tablename in c:DT.txt -c -Sservername -Usa -Ppassword'

导出文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" out c:DT.txt -c -Sservername -Usa -Ppassword'

此句需加引号

 

 

 

4.11、Excel导到Txt

想用

select *
into opendatasource(…) from opendatasource(…)

兑现将一个Excel文件内容导入到二个文件文件

 

若是Excel中有两列,第一名列姓名,第二列为很行帐号(16人)

且银行帐号导出到文本文件后分两有个别,前8位和后8位分别。

 

若是要用你上面的口舌插入的话,文本文件必需存在,並且有生龙活虎行:姓名,银行账号1,银行账号2

下一场就能够用上边包车型地铁言辞实行插队

小心文件名和目录依照你的莫过于意况打开改革.

www.qy186.com 58

insert into
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Text;HDR=Yes;DATABASE=C:'
)...[aa#txt]
--,aa#txt)
--*/

select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
from
opendatasource('MICROSOFT.JET.OLEDB.4.0'
,'Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:a.xls'
--,Sheet1$)
)...[Sheet1$]

www.qy186.com 59

 

 

设若您想直接插入并转移文书文件,将要用bcp

declare @sql varchar(8000),@tbname varchar(50) 

第意气风发将excel表内容导入到八个大局一时表

www.qy186.com 60

select @tbname='[##temp'+cast(newid() as varchar(40))+']'
,@sql='select 姓名,银行账号1=left(银行账号,8),银行账号2=right(银行账号,8)
into '+@tbname+' from
opendatasource(''MICROSOFT.JET.OLEDB.4.0''
,''Excel 5.0;HDR=YES;IMEX=2;DATABASE=c:a.xls''
)...[Sheet1$]'

exec(@sql)

www.qy186.com 61

接下来用bcp从全局临时表导出到文本文件

set @sql='bcp "'+@tbname+'" out "c:aa.txt" /S"(local)" /P"" /c'
exec master..xp_cmdshell @sql

去除临时表

exec('drop table '+@tbname) 

4.12、用bcp将文件导入导出到数据库的囤积进度:

bcp-二进制文件的导入导出

支撑image,text,ntext字段的导入/导出

image相符于二进制文件;text,ntext相符于文本数据文件

 

只顾:导入时,将掩瞒满足条件的保有行

导出时,将把装有满意条件的行也出到钦赐文件中

 

此存款和储蓄进度仅用bcp完结

 

/*–调用示例

–数据导出

exec p_binaryIO 'zj','','','acc_演示数据..tb','img','c:zj1.dat' 

–数据导出

exec p_binaryIO 'zj','','','acc_演示数据..tb','img','c:zj1.dat','',0

 

–*/

 

www.qy186.com 62View Code

 

 转移数据管理回复文件

www.qy186.com 63

set @m_tbname='[##temp'+cast(newid() as varchar(40))+']'
set @sql='select * into '+@m_tbname+' from(
select null as 类型
union all select 0 as 前缀
union all select '+@fsize+' as 长度
union all select null as 结束
union all select null as 格式
) a'

exec(@sql)

select @fname_in=@fname+'_temp'
,@sql='bcp "'+@m_tbname+'" out "'+@fname_in
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')+'" /c'

exec master..xp_cmdshell @sql

www.qy186.com 64

 

去除一时表

www.qy186.com 65

set @sql='drop table '+@m_tbname
exec(@sql)

if @isout=1
begin
set @sql='bcp "select top 1 '+@fdname+' from '
+@tbname+case isnull(@tj,'') when '' then ''
else ' where '+@tj end
+'" queryout "'+@fname
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')
+'" /i"'+@fname_in+'"'


exec master..xp_cmdshell @sql
end
else
begin

www.qy186.com 66

 

为数量导入计划有时表

set @sql='select top 0 '+@fdname+' into '
+@m_tbname+' from ' +@tbname

exec(@sql)

将数据导入到一时表

www.qy186.com 67

set @sql='bcp "'+@m_tbname+'" in "'+@fname
+'" /S"'+@servename
+case when isnull(@username,'')='' then ''
else '" /U"'+@username end
+'" /P"'+isnull(@password,'')
+'" /i"'+@fname_in+'"'

exec master..xp_cmdshell @sql

www.qy186.com 68

 

 将数据导入到正式表中

www.qy186.com 69

set @sql='update '+@tbname
+' set '+@fdname+'=b.'+@fdname
+' from '+@tbname+' a,'
+@m_tbname+' b'
+case isnull(@tj,'') when '' then ''
else ' where '+@tj end

exec(@sql)

www.qy186.com 70

剔除数据处理不时表

set @sql='drop table '+@m_tbname
end

删除数据管理答复文件

set @sql='del '+@fname_in

exec master..xp_cmdshell @sql
go

 

 导入文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" in c:DT.txt -c -Sservername -Usa -Ppassword'

改为如下,不需引号

EXEC master..xp_cmdshell 'bcp dbname..tablename in c:DT.txt -c -Sservername -Usa -Ppassword'

导出文本文件

EXEC master..xp_cmdshell 'bcp "dbname..tablename" out c:DT.txt -c -Sservername -Usa -Ppassword'

此句需加引号

相关文章