数据库中经常用到的操作和管理数据库的语句总结第1/2页
数据库中经常用到的操作和管理数据库的语句,感谢作者的辛勤劳动,很多。
/*
--整理者:永恒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'

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PyCharm is a very popular Python integrated development environment (IDE). It provides a wealth of functions and tools to make Python development more efficient and convenient. This article will introduce you to the basic operation methods of PyCharm and provide specific code examples to help readers quickly get started and become proficient in operating the tool. 1. Download and install PyCharm First, we need to go to the PyCharm official website (https://www.jetbrains.com/pyc

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

LinuxDeploy operating steps and precautions LinuxDeploy is a powerful tool that can help users quickly deploy various Linux distributions on Android devices, allowing users to experience a complete Linux system on their mobile devices. This article will introduce the operating steps and precautions of LinuxDeploy in detail, and provide specific code examples to help readers better use this tool. Operation steps: Install LinuxDeploy: First, install

Presumably many users have several unused computers at home, and they have completely forgotten the power-on password because they have not been used for a long time, so they would like to know what to do if they forget the password? Then let’s take a look together. What to do if you forget to press F2 for win10 boot password? 1. Press the power button of the computer, and then press F2 when turning on the computer (different computer brands have different buttons to enter the BIOS). 2. In the bios interface, find the security option (the location may be different for different brands of computers). Usually in the settings menu at the top. 3. Then find the SupervisorPassword option and click it. 4. At this time, the user can see his password, and at the same time find the Enabled next to it and switch it to Dis.

With the popularity of smartphones, the screenshot function has become one of the essential skills for daily use of mobile phones. As one of Huawei's flagship mobile phones, Huawei Mate60Pro's screenshot function has naturally attracted much attention from users. Today, we will share the screenshot operation steps of Huawei Mate60Pro mobile phone, so that everyone can take screenshots more conveniently. First of all, Huawei Mate60Pro mobile phone provides a variety of screenshot methods, and you can choose the method that suits you according to your personal habits. The following is a detailed introduction to several commonly used interceptions:

Apple brought some Pro-exclusive hardware features to iPhone 15 Pro and 15 Pro Max, which attracted everyone’s attention. We're talking titanium frames, sleek designs, the new A17 Pro chipset, an exciting 5x telephoto lens, and more. Of all the bells and whistles added to the iPhone 15 Pro models, the action button remains a prominent and prominent feature. Needless to say, it is a useful addition to launching actions on your iPhone. That said, you could accidentally hold down the Action button and trigger the feature inadvertently. Frankly, it's annoying. To avoid this, you should disable the action button on iPhone 15 Pro and 15 Pro Max. let

CSS web page scroll monitoring: monitor web page scroll events and perform corresponding operations. With the continuous development of front-end technology, the effects and interactions of web pages are becoming more and more rich and diverse. Among them, scroll monitoring is a common technology that can perform some special effects or operations based on the scroll position when the user scrolls the web page. Generally speaking, scroll monitoring can be implemented through JavaScript. However, in some cases, we can also achieve the effect of scroll monitoring through pure CSS. This article will introduce how to implement scrolling of web pages through CSS

Apple's iPhone 15 Pro and iPhone 15 Pro Max introduce a new programmable action button that replaces the traditional ring/silent switch above the volume buttons. Read on to learn what the Action button does and how to customize it. A new action button on Apple iPhone 15 Pro models replaces the traditional iPhone switch that activates Ring and Silent. By default, the new button will still activate both functions with a long press, but you can also have a long press perform a range of other functions, including quick access to the camera or flashlight, activating voice memos, focus mode, translation, and accessibility features like magnifier . You can also associate it with a single shortcut, opening up a ton of other possibilities
