Mysql Sql语句注释大全实例( 三 )


U代表用户
21、说明:列出表里的所有的列名
select name from syscolumnswhere id=object_id('TableName')
22、说明:列示type、vender、pcs字段 , 以type字段排列 , case可以方便地实现多重选择 , 类似select 中的case 。
select type,sum(case venderwhen 'A' then pcselse 0end),sum(case venderwhen 'C' then pcselse 0end),sum(case venderwhen 'B' then pcselse 0end)FROM tablenamegroup 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 idasc)
table_别名 order by iddesc
三、技巧
1、1=1 , 1=2的使用 , 在SQL语句组合时用的较多
“where 1=1”
是表示选择全部 “where 1=2”全部不选 , 
如:
if
@strWhere !=''
begin
set @strSQL
= 'select
count(*) as Total from [' +
@tblName + ']
where ' +
@strWhere
end
else
begin
set @strSQL
= 'select
count(*) as Total from [' +
@tblName + ']'
end
我们可以直接写成
错误!未找到目录项 。
set @strSQL
= 'select
count(*) as Total from [' +
@tblName + ']
where 1=1 安定 '+
@strWhere 2、收缩数据库
--重建索引
DBCC
REINDEX
DBCC
INDEXDEFRAG
--收缩数据和日志
DBCC
SHRINKDB
DBCC
SHRINKFILE
3、压缩数据库
dbcc
shrinkdatabase(dbname)
4、转移数据库给新用户以已存在用户权限
exec sp_change_users_login'update_one','newname','oldname'
go
5、检查备份集
RESTORE
VERIFYONLY from disk='E:dvbbs.bak'
6、修复数据库
ALTER DATABASE [dvbbs]SET SINGLE_USER
GO
DBCC
CHECKDB('dvbbs',repair_allow_data_loss)WITH TABLOCK
GO
ALTER DATABASE [dvbbs]SET MULTI_USER
GO
7、日志清除
SET NOCOUNTON
DECLARE @LogicalFileName
sysname,
@MaxMinutesINT,
@NewSizeINT
USE
tablename --
要操作的数据库名
SELECT @LogicalFileName
= 'tablename_log',--
日志文件名
@MaxMinutes
= 10, --
Limit on time allowed to wrap log.
@NewSize
= 1 --
你想设定的日志文件的大小(M)
Setup
/ initialize
DECLARE @OriginalSizeint
SELECT @OriginalSize
= size
FROM sysfiles
WHERE name =
@LogicalFileName
SELECT 'Original
Size of ' +
db_name() + '
LOG is ' +
CONVERT(VARCHAR(30),@OriginalSize)
+ '
8K pages or ' +
CONVERT(VARCHAR(30),(@OriginalSize*8/1024))
+ 'MB'
FROM sysfiles
WHERE name =
@LogicalFileName
CREATE TABLE DummyTrans
(DummyColumnchar (8000)not null)
DECLARE @Counter INT,
@StartTime
DATETIME,
@TruncLog VARCHAR(255)
SELECT @StartTime
= GETDATE(),
@TruncLog
= 'BACKUP
LOG ' +
db_name() + '
WITH TRUNCATE_ONLY'
DBCC
SHRINKFILE (@LogicalFileName, @NewSize)
EXEC (@TruncLog)
--
Wrap the log if necessary.
WHILE
@MaxMinutes > DATEDIFF (mi, @StartTime, GETDATE()) --
time has not expired
AND @OriginalSize
= (SELECT size FROM sysfilesWHERE name =
@LogicalFileName)
AND (@OriginalSize
* 8 /1024) > @NewSize
BEGIN --
Outer loop.
SELECT @Counter
= 0
WHILE
((@Counter < @OriginalSize / 16) AND (@Counter
< 50000))
BEGIN --
update
INSERT DummyTransVALUES ('Fill
Log')DELETE DummyTrans
SELECT @Counter
= @Counter + 1
END
EXEC (@TruncLog)
END
SELECT 'Final
Size of ' +
db_name() + '
LOG is ' +
CONVERT(VARCHAR(30),size)
+ '
8K pages or ' +
CONVERT(VARCHAR(30),(size*8/1024))
+ 'MB'
FROM sysfiles
WHERE name =
@LogicalFileName
DROP TABLE DummyTrans
SET NOCOUNTOFF
8、说明:更改某个表
exec sp_changeobjectowner'tablename','dbo'
9、存储更改全部表
CREATE PROCEDURE dbo.User_ChangeObjectOwnerBatch


推荐阅读