澳门新萄京SQL SEHavalVE安德拉常用语法汇总

4.10.1、导出调用示例

—-导出单个表

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

 

—-导出一切数据库

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

 

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:
全外连接:不止囊括符号连接表的相称行,还包蕴八个接二连三表中的全体记录。

 

20、表明:列出数据Curry装有的表名

 

澳门新萄京 1

澳门新萄京 2

 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

澳门新萄京 3

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

 

澳门新萄京 4澳门新萄京 5

 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

9、存款和储蓄改动全体表

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.未知列名查全部在区别表现身过的列名

澳门新萄京 6

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
)

澳门新萄京 7

 

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.7、通过SQL语句来改动顾客的密码

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

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

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

二、基础语句

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'

 

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
 1 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
 2 
 3 --显示结果:
 4 
 5   type vender pcs
 6 
 7   电脑 A 1
 8 
 9   电脑 A 1
10 
11   光盘 B 2
12 
13   光盘 A 2
14 
15   手机 B 3
16 
17   手机 C 3

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表的公文名.

 

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.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)
1 select * from master..sysdatabases D where sid not in(select sid from master..syslogins where name='sa')
2 
3 --或者
4 
5 select dbid, name AS DB_NAME from master..sysdatabases where sid <> 0x01

3.2、查询数据的最大排序问题(只可以用一条语句写)

澳门新萄京 8

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)

澳门新萄京 9

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

澳门新萄京 10

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语句。

澳门新萄京 11

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

2.1、说明:创造数据库

create database db-name

 

1 select top 10 * from tablename order by newid()

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

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.1、导出到excel

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

 

22、表达:列示type、vender、pcs字段,以type字段排列,case能够方便地完成多种选用,类似select
中的case

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]

 

注:行数为相对行数

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]')
--*/

二、基础语句

1    select encrypt('原始密码')
2 
3   select pwdencrypt('原始密码')
4 
5   select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 encrypt('原始密码')
6 
7   select pwdencrypt('原始密码')
8 
9   select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 

4.10、导整个数据库

用bcp完结的贮存进度

福寿康宁数量导入/导出的仓库储存进程

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

调用示例:

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

 

 

1 create [unique] index idxname on tabname(col….)
2 
3 --删除索引:drop index idxname
4 
5 --注:索引是不可更改的,想更改必须删除重新建。

2.5、表达:删除新表

drop table tabname

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

创建一个联结的函数

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.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
)

 

2、收缩数据库

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

澳门新萄京 12

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

澳门新萄京 13

三、sql技巧

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))。

 

  1、表明:创造数据库

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

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

 

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

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

 

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.3、求删除重复记录的sql语句

什么把具备同样字段的记录删除,只留下一条。

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

一经有name相同的记录
只留下一条,别的的删减。

name的剧情不定,一样的记录数不定。

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

三个总体的消除方案:

澳门新萄京 14

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

澳门新萄京 15

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
)

 

4.5、导入DBF文件

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

 

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

3.6、如何收获二个数据表的兼具列名

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

SQL语句如下:

澳门新萄京 16

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

澳门新萄京 17

或 

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

 

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

3.8、怎么判定出叁个表的什么样字段不允许为空

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

 

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

4.8、导入Access

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

 

 

4.11、Excel导到Txt

想用

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

贯彻将三个Excel文件内容导入到贰个文件文件

 

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

且银行帐号导出到文本文件后分两部分,前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) 

  6、表达:扩大三个列

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

 

–*/

 

澳门新萄京 18View Code

 

 变化数据管理答复文件

澳门新萄京 19

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

澳门新萄京 20

 

去除有时表

澳门新萄京 21

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

澳门新萄京 22

 

为多少导入盘算一时表

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

exec(@sql)

将数据导入到有的时候表

澳门新萄京 23

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

澳门新萄京 24

 

 将数据导入到正式表中

澳门新萄京 25

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)

澳门新萄京 26

删除数据管理一时表

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.10.2、导入调用示例

—-导入单个表

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

 

—-导入整个数据库

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

2.11、表达:高等查询运算

A: UNION
运算符

UNION
运算符通过结合其他八个结果表(比方 TABLE1 和
TABLE2)并消去表中别的重复行而派生出八个结实表。

当 ALL 随
UNION 一同利用时(即 UNION ALL),不清除重复行。

两种境况下,派生表的每一行不是缘于
TABLE1 就是源于 TABLE2。

B:
EXCEPT 运算符

EXCEPT
运算符通过满含持有在 TABLE1 中但不在 TABLE2中的行并化解全数重复行而派生出一个结出表。

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

C:
INTERSECT 运算符

INTE奥迪Q5SECT
运算符通过只包涵 TABLE1 和 TABLE2中都局地行并消除全数重复行而派生出三个结实表。

当 ALL 随
INTEMuranoSECT 一同利用时 (INTE悍马H2SECT ALL),不拔除重复行。

注:使用运算词的多少个查询结果行必需是千篇一律的。

1 select column_name,data_type from information_schema.columns
2 where table_name = '表名'

3.5、行列转变–合併

澳门新萄京 27

有表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

澳门新萄京 28

开创多个统一的函数

澳门新萄京 29

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

澳门新萄京 30

调用自定义函数获得结果

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

 

一、SQL分类

DDL—数据定义语言(CREATE,ALTE昂科雷,DROP,DECLARE)

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

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

 

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]

 

注:行数为相对行数

 1    if (select checksum_agg(binary_checksum(*)) from A)
 2 
 3   =
 4 
 5   (select checksum_agg(binary_checksum(*)) from B)
 6 
 7   print '相等'
 8 
 9   else
10 
11   print '不相等'

开卷目录

4.9、 导入 xml文件

 

澳门新萄京 31澳门新萄京 32

 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

 

 

 

2.5、表明:删除新表

drop table tabname

  10、表明:多少个简易的中坚的sql语句

4.5、导入DBF文件

澳门新萄京 33

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

澳门新萄京 34

 

2.2、表明:删除数据库

drop database db-name 

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

一、提升

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

澳门新萄京 35

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

澳门新萄京 36

4.5、导入DBF文件

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

 

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
1 select top 10 recid from A where recid not in(select top 30 recid from A)

4.1、导出到excel

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

 

2.3、说明:备份sql server

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

4.8、导入Access

insert into B表 selet * from openrowset('Microsoft.Jet.OLEDB.4.0',
'x:\A.mdb';'admin';'',A表)
1 select name from syscolumns where id=object_id('TableName')

3.4、行列转变–普通

澳门新萄京 37

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

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

想变成

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

澳门新萄京 38

澳门新萄京 39

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)

澳门新萄京 40

 

澳门新萄京 41澳门新萄京 42

 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

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

 存款和储蓄进度如下:

澳门新萄京 43澳门新萄京 44

 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

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

4.3、 导入文本文件

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

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

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
 1    ALTER DATABASE [dvbbs] SET SINGLE_USER
 2 
 3   GO
 4 
 5   DBCC CHECKDB('dvbbs',repair_allow_data_loss) WITH TABLOCK
 6 
 7   GO
 8 
 9   ALTER DATABASE [dvbbs] SET MULTI_USER
10 
11   GO

四、(MS SQL Server)SQL语句导入导出大全

补充:

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)、表达:一条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)、表明:选择在每一组b值一样的多寡中对应的a最大的记录的全数音讯(类似这样的用法能够用来论坛每月排名榜,每月紧俏产品解析,按学科成绩排名,等等.)

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

16)、表达:包罗全数在
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.3、说明:备份sql server

--- 创建 备份
USE master
EXEC sp_addumpdevice 'disk', 'testBack', 'c:mssql7backupMyNwind_1.dat'
--- 开始 备份
BACKUP DATABASE pubs TO testBack
1 --- 创建 备份数据的 device
2 
3   USE master
4 
5   EXEC sp_addumpdevice 'disk', 'testBack', 'c:\mssql7backup\MyNwind_1.dat'
6 
7   --- 开始 备份
8 
9   BACKUP DATABASE pubs TO testBack

2.3、说明:备份sql server

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

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]

 

注:行数为相对行数

4.3、 导入文本文件

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

  在SQLServer中分组时:无法以text,ntext,image类型的字段作为分组依附

3.14、快捷获得表test的记录总的数量[对大容积表特别平价]

快快取得表test的记录总数:

澳门新萄京 45

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)

澳门新萄京 46

回去目录

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)

2.1、表明:创设数据库

create database db-name

  组相关的新闻:(总计新闻) count,sum,max,min,avg 分组的标准)

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:
全外连接:不止包涵符号连接表的相称行,还满含三个接二连三表中的全体记录。

 

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 

  INTE大切诺基SECT 运算符通过只包括 TABLE1 和 TABLE第22中学都有的行并化解全数重复行而派生出八个结出表。当 ALL 随 INTE福睿斯SECT
一齐使用时 (INTEOdysseySECT ALL),不排除重复行。

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 随
INTETucsonSECT 一同使用时 (INTEEnclaveSECT ALL),不清除重复行。

注:使用运算词的几个查询结果行必需是一样的。

4.1、导出到excel

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

 

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

开创四个合併的函数

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

 

1 dbcc shrinkdatabase(dbname)

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

澳门新萄京 47

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

澳门新萄京 48

 存款和储蓄进度如下:

澳门新萄京 49

澳门新萄京 50

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

澳门新萄京 51

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

 存款和储蓄进程如下:

澳门新萄京 52澳门新萄京 53

 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

一、SQL分类

DDL—数据定义语言(CREATE,ALTE奥迪Q5,DROP,DECLARE)

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

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

 

9、表明:in
的使用办法

3.11、日期总结

澳门新萄京 54

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))。

澳门新萄京 55

 

2.11、表达:高端查询运算

A: UNION
运算符

UNION
运算符通过整合其余多少个结实表(比方 TABLE1 和
TABLE2)并消去表中别的重复行而派生出一个结实表。

当 ALL 随
UNION 一同利用时(即 UNION ALL),不免除重复行。

三种状态下,派生表的每一行不是源于
TABLE1 就是源于 TABLE2。

B:
EXCEPT 运算符

EXCEPT
运算符通过满含具备在 TABLE1 中但不在 TABLE2中的行并化解全部重复行而派生出四个结实表。

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

C:
INTERSECT 运算符

INTEEvoqueSECT
运算符通过只包罗 TABLE1 和 TABLE第22中学都有的行并化解全体重复行而派生出多个结实表。

当 ALL 随
INTE途锐SECT 一齐利用时 (INTETucsonSECT ALL),不免除重复行。

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

补充:

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)、表达:一条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)、表明:采纳在每一组b值同样的数目中对应的a最大的笔录的具备消息(类似那样的用法能够用于论坛每月名次榜,每月紧俏产品剖判,按学科成绩排行,等等.)

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

16)、说明:包含富有在
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、表明:删除数据库

归来目录

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;第一行不当成标题行

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表的公文名.

 

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

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

澳门新萄京 56

查询: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

澳门新萄京 57

3.7、通过SQL语句来更换顾客的密码

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

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

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;第一行不当成标题行
drop database dbname

4.2、 导入Excel

澳门新萄京 58

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;第一行不当成标题行

澳门新萄京 59

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))。

 

四、(MS SQL Server)SQL语句导入导出大全

CREATE DATABASE database-name
  • 一、SQL分类
  • 二、基础语句
  • 三、sql技巧
  • 四、(MS SQL
    Server)SQL语句导入导出大全

二、基础语句

三、sql技巧

17、说明:随机抽出10条数据

4.10.2、导入调用示例

—-导入单个表

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

 

—-导入整个数据库

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

4.3、 导入文本文件

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

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)

  在selecte总计函数中的字段,不能够和平时性的字段放在一块儿;

4.4、 导出文件文件

澳门新萄京 60

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

澳门新萄京 61

 

 补充:

澳门新萄京 62

--/* 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]')
--*/

澳门新萄京 63

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.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

6.杀掉全数的平地风波探察器进度

2.2、表达:删除数据库

drop database db-name 

4.11、Excel导到Txt

想用

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

福寿年高将四个Excel文件内容导入到一个文书文件

 

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

且银行帐号导出到文本文件后分两有的,前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.7、导出到Access

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

  8、表明:创立索引

2.1、表明:创造数据库

create database db-name

4.10、导整个数据库

用bcp落成的积累进度

完结数据导入/导出的仓库储存进程

听闻分歧的参数,能够兑现导入/导出整个数据库/单个表

调用示例:

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)

9:获取当前数据库中的全部客户表

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.5、表达:删除新表

drop table tabname

4.10、导整个数据库

用bcp完结的蕴藏进度

完结数量导入/导出的储存进度

遵照区别的参数,可以兑现导入/导出整个数据库/单个表

调用示例:

C: INTERSECT 运算符

 

 

4.7、导出到Access

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

2.2、表明:删除数据库

drop database db-name 

5、检查备份集

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图