Home > Database > Mysql Tutorial > body text

数据库中经常用到的操作和管理数据库的语句总结第1/2页

WBOY
Release: 2016-06-07 18:00:21
Original
676 people have browsed it

数据库中经常用到的操作和管理数据库的语句,感谢作者的辛勤劳动,很多。

/*
--整理者:永恒de影

--整理时间:2010/06/08

--内容:SQL函数的介绍:
*/

--★★SQL2000查询出各(某)表字段的属性:★★★★★★★★★★★★★★★★★★

SELECT
表名 = case when a.colorder=1 then d.name else '' end,
表说明 = case when a.colorder=1 then isnull(f.value,'') else '' end,
字段序号 = a.colorder,
字段名 = a.name,
标识 = case when COLUMNPROPERTY( a.id,a.name,'IsIdentity')=1 then '√'else '' end,
主键 = case when exists(SELECT 1 FROM sysobjects where xtype='PK' and parent_obj=a.id and name in (
SELECT name FROM sysindexes WHERE indid in(
SELECT indid FROM sysindexkeys WHERE id = a.id AND colid=a.colid))) then '√' else '' end,
类型 = b.name,
占用字节数 = a.length,
长度 = COLUMNPROPERTY(a.id,a.name,'PRECISION'),
小数位数 = isnull(COLUMNPROPERTY(a.id,a.name,'Scale'),0),
允许空 = case when a.isnullable=1 then '√'else '' end,
默认值 = isnull(e.text,''),
字段说明 = isnull(g.[value],'')
FROM
syscolumns a
left join
systypes b
on
a.xusertype=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
left join
sysproperties f
on
d.id=f.id and f.smallid=0
where
d.name='要查询的表' --如果只查询指定表,加上此条件
order by
a.id,a.colorder


--★★SQL2005查询出各(某)表字段的属性:★★★★★★★★★★★★★★★★★★
-- ========================================================================
-- 表结构信息查询
-- 邹建 2005.08(引用请保留此信息)
-- ========================================================================
SELECT
TableName=CASE WHEN C.column_id=1 THEN O.name ELSE N'' END,
TableDesc=ISNULL(CASE WHEN C.column_id=1 THEN PTB.[value] END,N''),
Column_id=C.column_id,
ColumnName=C.name,
PrimaryKey=ISNULL(IDX.PrimaryKey,N''),
[IDENTITY]=CASE WHEN C.is_identity=1 THEN N'√'ELSE N'' END,
Computed=CASE WHEN C.is_computed=1 THEN N'√'ELSE N'' END,
Type=T.name,
Length=C.max_length,
Precision=C.precision,
Scale=C.scale,
NullAble=CASE WHEN C.is_nullable=1 THEN N'√'ELSE N'' END,
[Default]=ISNULL(D.definition,N''),
ColumnDesc=ISNULL(PFD.[value],N''),
IndexName=ISNULL(IDX.IndexName,N''),
IndexSort=ISNULL(IDX.Sort,N''),
Create_Date=O.Create_Date,
Modify_Date=O.Modify_date
FROM sys.columns C
INNER JOIN sys.objects O
ON C.[object_id]=O.[object_id]
AND O.type='U'
AND O.is_ms_shipped=0
INNER JOIN sys.types T
ON C.user_type_id=T.user_type_id
LEFT JOIN sys.default_constraints D
ON C.[object_id]=D.parent_object_id
AND C.column_id=D.parent_column_id
AND C.default_object_id=D.[object_id]
LEFT JOIN sys.extended_properties PFD
ON PFD.class=1
AND C.[object_id]=PFD.major_id
AND C.column_id=PFD.minor_id
-- AND PFD.name='Caption' -- 字段说明对应的描述名称(一个字段可以添加多个不同name的描述)
LEFT JOIN sys.extended_properties PTB
ON PTB.class=1
AND PTB.minor_id=0
AND C.[object_id]=PTB.major_id
-- AND PFD.name='Caption' -- 表说明对应的描述名称(一个表可以添加多个不同name的描述)
LEFT JOIN -- 索引及主键信息
(
SELECT
IDXC.[object_id],
IDXC.column_id,
Sort=CASE INDEXKEY_PROPERTY(IDXC.[object_id],IDXC.index_id,IDXC.index_column_id,'IsDescending')
WHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END,
PrimaryKey=CASE WHEN IDX.is_primary_key=1 THEN N'√'ELSE N'' END,
IndexName=IDX.Name
FROM sys.indexes IDX
INNER JOIN sys.index_columns IDXC
ON IDX.[object_id]=IDXC.[object_id]
AND IDX.index_id=IDXC.index_id
LEFT JOIN sys.key_constraints KC
ON IDX.[object_id]=KC.[parent_object_id]
AND IDX.index_id=KC.unique_index_id
INNER JOIN -- 对于一个列包含多个索引的情况,只显示第1个索引信息
(
SELECT [object_id], Column_id, index_id=MIN(index_id)
FROM sys.index_columns
GROUP BY [object_id], Column_id
) IDXCUQ
ON IDXC.[object_id]=IDXCUQ.[object_id]
AND IDXC.Column_id=IDXCUQ.Column_id
AND IDXC.index_id=IDXCUQ.index_id
) IDX
ON C.[object_id]=IDX.[object_id]
AND C.column_id=IDX.column_id
-- WHERE O.name=N'要查询的表' -- 如果只查询指定表,加上此条件
ORDER BY O.name,C.column_id

--★★SQL2005索引及主键信息 :★★★★★★★★★★★★★★★★★★
-- ========================================================================
-- 索引及主键信息
-- 邹建 2005.08(引用请保留此信息)
-- ========================================================================
SELECT
TableId=O.[object_id],
TableName=O.Name,
IndexId=ISNULL(KC.[object_id],IDX.index_id),
IndexName=IDX.Name,
IndexType=ISNULL(KC.type_desc,'Index'),
Index_Column_id=IDXC.index_column_id,
ColumnID=C.Column_id,
ColumnName=C.Name,
Sort=CASE INDEXKEY_PROPERTY(IDXC.[object_id],IDXC.index_id,IDXC.index_column_id,'IsDescending')
WHEN 1 THEN 'DESC' WHEN 0 THEN 'ASC' ELSE '' END,
PrimaryKey=CASE WHEN IDX.is_primary_key=1 THEN N'√'ELSE N'' END,
[UQIQUE]=CASE WHEN IDX.is_unique=1 THEN N'√'ELSE N'' END,
Ignore_dup_key=CASE WHEN IDX.ignore_dup_key=1 THEN N'√'ELSE N'' END,
Disabled=CASE WHEN IDX.is_disabled=1 THEN N'√'ELSE N'' END,
Fill_factor=IDX.fill_factor,
Padded=CASE WHEN IDX.is_padded=1 THEN N'√'ELSE N'' END
FROM sys.indexes IDX
INNER JOIN sys.index_columns IDXC
ON IDX.[object_id]=IDXC.[object_id]
AND IDX.index_id=IDXC.index_id
LEFT JOIN sys.key_constraints KC
ON IDX.[object_id]=KC.[parent_object_id]
AND IDX.index_id=KC.unique_index_id
INNER JOIN sys.objects O
ON O.[object_id]=IDX.[object_id]
INNER JOIN sys.columns C
ON O.[object_id]=C.[object_id]
AND O.type='U'
AND O.is_ms_shipped=0
AND IDXC.Column_id=C.Column_id


--★★SQL Server对大容量内存的支持:★★★★★★★★★★★★★★★★★★

/*
32位操作系统有个很大的缺陷,应用程序无法访问大于4G的进程地址空间,因为32位的指针无法保存大于4G的地址空间
如果大于4G,则需要使用地址窗口化扩展插件(AWE),具体操作如下:
1,启动物理地址扩展
(1)找到C:\boot.ini,并删除其只读属性.
(2)编辑boot.ini,在ARC路径中添加/PAE参数.例如:
在windows Server 2003 Enterprise Edition 中,编辑后的ARC路径如下:
muti(0)disk(0)partition(1)windows="windows Server 2003 Enterprise,Edition"/fastdetect/PAE
保存后将其恢复为只读模式,然后重新启动计算机。

如果计算机上的可用物理内存超过16G,应确保boot.ini文件中没有/3gb参数
*/

--★★如何启动AWE选项:★★★★★★★★★★★★★★★★★★

sp_configure'show advanced options',1
reconfigure
go
sp_configue 'awe enabled',1
reconfigure
go

--★★手动配置内存选项:★★★★★★★★★★★★★★★★★★

sp_configure'show advanced options',1
go
reconfigure
go
sp_configure 'min server memory' --服务器最小内存
sp_configure 'max server memory' --服务器最大内存
sp_configure 'index create memory'--创建索引占用的内存
sp_configure 'min memory per query'--每次查询占用的最小内存


--★★获取磁盘读写情况:★★★★★★★★★★★★★★★★★★

select
@@total_read as '读取磁盘的次数',
@@total_write as '写入磁盘的次数',
@@total_error as '磁盘写入错误数',
getdate() as '当前时间'

--★★获取数据库文件的I/O统计信息:★★★★★★★★★★★★★★★★★★

select * from fn_virtualfilestats(null,null)

--★★获取I/O工作情况:★★★★★★★★★★★★★★★★★★

select
@@id_busy,--SQL自上次启动以来的用于执行输入和输出操作的时间
@@timeticks, --每个时钟周期对应的微秒数
@@id_busy*@@timeticks as 'I/O 操作毫秒数',
getdate() as '当前时间'

--★★查看SQL SEVER CPU活动,工作情况:★★★★★★★★★★★★★★★★★★

select
@@cpu_busy,--自上次启动以来的工作时间
@@timeticks, --每个时钟周期对应的微秒数
@@cpu_busy*cast(@@timeticks as float)/1000 as 'cpu工作时间(秒)',
@@idie*cast(@@timeticks as float)/1000 as 'CPU空闲时间(秒)'
getdate() as '当前时间'

--★★获取网络数据包统计信息:★★★★★★★★★★★★★★★★★★

select
getdate() as '当前时间',
@@pack_received as'输入数据包数量',
@@pack_sent as '输出数据包数量',
@@packet_error as '错误包数量'


--★★查看服务器工作状态:★★★★★★★★★★★★★★★★★★

create function fgetsstatus(
@servername varchar(50) --服务器名
,@userid varchar(50)='sa' --用户名,如果为nt验证方式,则为空
,@password varchar(50)='' --密码

) returns varchar(20)
as
begin
declare @re varchar(20),@ire int --返回状态
declare @srvid int --定义服务器、数据库集id
declare @err int,@src varchar(255), @desc varchar(255) --错误处理变量

--★★创建sqldmo对象 :★★★★★★★★★★★★★★★★★★

exec @err=sp_oacreate 'sqldmo.sqlserver',@srvid output
if @err 0 goto lberr

--★★连接服务器 :★★★★★★★★★★★★★★★★★★

if isnull(@userid,'')='' --如果是 Nt验证方式
begin
exec @err=sp_oasetproperty @srvid,'loginsecure',1
if @err 0 goto lberr

exec @err=sp_oamethod @srvid,'connect',null,@servername
end
else
exec @err=sp_oamethod @srvid,'connect',null,@servername,@userid,@password

if @err 0 goto lberr

--★★获取服务器状态 :★★★★★★★★★★★★★★★★★★

exec @err=sp_oagetproperty @srvid,'Status',@ire output
if @err 0 goto lberr

set @re=case @ire when 0 then '未知'
when 1 then '运行...'
when 2 then '暂停'
when 3 then '停止...'
when 4 then '正在启动...'
when 5 then '正在启动停止...'
when 6 then '连接...'
when 7 then '正在暂停...' end
return(@re)
lberr:
exec sp_oageterrorinfo NULL, @src out, @desc out
declare @errb varbinary(4)
set @errb=cast(@err as varbinary(4))
exec master..xp_varbintohexstr @errb,@re out
set @re='错误号: '+@re
+char(13)+'错误源: '+@src
+char(13)+'错误描述: '+@desc
return(@re)
end
go

select dbo.fgetsstatus('192.168.102.208','sa','sa')

--------------------
--运行...

--★★获取服务器状态 :★★★★★★★★★★★★★★★★★★

if object_id('tb')is not null drop table tb
go
create table tb(
表名 sysname,
记录数 int,
保留空间 nvarchar(10),
使用空间 varchar(10),
索引使用空间 varchar(10),
未用空间 varchar(10))
exec sp_MSForEachTable @command1=N'insert tb exec sp_spaceused ''?'''

select * from tb

--★★查看服务器版本 :★★★★★★★★★★★★★★★★★★

SELECT
SERVERPROPERTY('productversion'),
SERVERPROPERTY ('productlevel'),
SERVERPROPERTY ('edition')

--★★查看数据库脱机时间 :★★★★★★★★★★★★★★★★★★

EXEC sp_configure 'show advanced options', 1
RECONFIGURE
go
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
select a.name,a.database_id,a.create_date,b.physical_name into #a
from sys.databases a left join sys.master_files b on
a.database_id=b.database_id where has_dbaccess(a.name)1 and b.type=1

create table #b(info varchar(500))
declare @string varchar(max)
set @string=''
select @string=@string+'insert into #b exec xp_cmdshell''dir '+ physical_name +''''+char(13)+char(10) from #a
execute(@string)

select a.name,substring(b.info,0,20) as 脱机时间,a.database_id,a.create_date,a.physical_name
from #a a left join #b b on
REVERSE(substring(REVERSE(physical_name),0,charindex('\',REVERSE(physical_name))))
=REVERSE(substring(REVERSE(info),0,charindex(' ',REVERSE(info))))

drop table #a,#b
go
EXEC sp_configure 'xp_cmdshell', 0
RECONFIGURE
go
EXEC sp_configure 'show advanced options', 0
RECONFIGURE
go

/*

1. 查看数据库的版本

select @@version

2.查看数据库所在机器操作系统参数 .

exec master..xp_msver ..

3. 查看数据库启动的参数 !

sp_configure
4.查看数据库启动时间 .

select convert(varchar(30),login_time,120) from master..sysprocesses where spid=1

查看数据库服务器名和实例名 .

print ''Server Name...............: '' + convert(varchar(30),@@SERVERNAME) .

print ''Instance..................: '' + convert(varchar(30),@@SERVICENAME) ...

5. 查看所有数据库名称及大小

sp_helpdb 。

重命名数据库用的SQL

sp_renamedb ''old_dbname'', ''new_dbname''

6. 查看所有数据库用户登录信息 ..

sp_helplogins

查看所有数据库用户所属的角色信息

sp_helpsrvrolemember !

修复迁移服务器时孤立用户时,可以用的fix_orphan_user脚本或者LoneUser过程 .

更改某个数据对象的用户属主

sp_changeobjectowner [@objectname =] ''object'', [@newowner =] ''owner'' .

注意: 更改对象名的任一部分都可能破坏脚本和存储过程。

把一台服务器上的数据库用户登录信息备份出来可以用add_login_to_aserver脚本

7. 查看链接服务器 ...

sp_helplinkedsrvlogin

查看远端数据库用户登录信息 。

sp_helpremotelogin ..

8.查看某数据库下某个数据对象的大小 !

sp_spaceused @objname

还可以用sp_toptables过程看最大的N(默认为50)

*/

--★★查看作业执行情况 :★★★★★★★★★★★★★★★★★★

select category = jc.name,
category_id = jc.category_id,
job_name = j.name,
job_enabled = j.enabled,
last_run_time = cast(js.last_run_date as varchar(10)) + '-' + cast(js.last_run_time as varchar(10)),
last_run_duration = js.last_run_duration,
last_run_status = js.last_run_outcome,
last_run_msg = js.last_outcome_message + cast(nullif(js.last_run_outcome,1) as varchar(2)),
job_created = j.date_created,
job_modified = j.date_modified
from msdb.dbo.sysjobs j
inner join msdb.dbo.sysjobservers js
on j.job_id = js.job_id
inner join msdb.dbo.syscategories jc
on j.category_id = jc.category_id
where j.enabled = 1
and js.last_run_outcome in (0,1,3,5) -- 0:Fail 1:Succ 3:Cancel 5:First run
and jc.category_id not between 10 and 20 -- repl

--★★查询数据库db中表tb的所有索引的随片情况 :★★★★★★★★★★★★★★★★★★

use db
go
select
a.index_id,---索引编号
b.name,---索引名称
avg_fragmentation_in_percent---索引的逻辑碎片
from
sys.dm_db_indx_physical_stats(db_id(),object_id(N'create.consume'),null,null,null) as a
join
sys.indexes as b
on
a.object_id=b.object_id
and
a.index_id=b.index_id
go

--★★用户成员权限:★★★★★★★★★★★★★★★★★★

USE pubs

--创建角色 r_test
EXEC sp_addrole 'r_test'

--授予 r_test 对 jobs 表的所有权限
GRANT ALL ON jobs TO r_test
--授予角色 r_test 对 titles 表的 SELECT 权限
GRANT SELECT ON titles TO r_test

--添加登录 l_test,设置密码为pwd,默认数据库为pubs
EXEC sp_addlogin 'l_test','pwd','pubs'

--为登录 l_test 在数据库 pubs 中添加安全账户 u_test
EXEC sp_grantdbaccess 'l_test','u_test'

--添加 u_test 为角色 r_test 的成员
EXEC sp_addrolemember 'r_test','u_test'

--拒绝安全账户 u_test 对 titles 表的 SELECT 权限
DENY SELECT ON titles TO u_test

/*--完成上述步骤后,用 l_test 登录,可以对jobs表进行所有操作,但无法对titles表查询,虽然角色 r_test 有titles表的select权限,但已经在安全账户中明确拒绝了对titles的select权限,所以l_test无titles表的select权限--*/

--从数据库 pubs 中删除安全账户
EXEC sp_revokedbaccess 'u_test'

--删除登录 l_test
EXEC sp_droplogin 'l_test'

--删除角色 r_test
EXEC sp_droprole 'r_test'

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template