热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

几个有用的T-SQL(1)

清除所有表记录,有点像RESET,保留constraints与identities.--DisableConstraints&TriggersEXECsp_MS
  1. 清除所有表记录,有点像RESET,保留constraints与identities.
--Disable Constraints & Triggers  
EXEC sp_MSforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' 
EXEC sp_MSforeachtable 'ALTER TABLE ? DISABLE TRIGGER ALL' 
--Perform delete operation on all table for cleanup  
EXEC sp_MSforeachtable 'DELETE ?' 
--Enable Constraints & Triggers again  
EXEC sp_MSforeachtable 'ALTER TABLE ? CHECK CONSTRAINT ALL' 
EXEC sp_MSforeachtable 'ALTER TABLE ? ENABLE TRIGGER ALL' 
--Reset Identity on tables with identity column  
EXEC sp_MSforeachtable 'IF OBJECTPROPERTY(OBJECT_ID(''?''), ''TableHasIdentity'') = 1  
BEGIN DBCC CHECKIDENT (''?'',RESEED,0) END' 

 

  2.    列出DB中表的大小,所占磁盘大小。

CREATE PROCEDURE [dbo].[GetDBTableSize]  
AS 
BEGIN 
SET NOCOUNT ON;  
DECLARE @cmdstr varchar(100)  
--Create Temporary Table  
CREATE TABLE #TempTable  
(  
    [Table_Name] varchar(50),  
    Row_Count int,  
    Table_Size varchar(50),  
    Data_Space_Used varchar(50),  
    Index_Space_Used varchar(50),  
    Unused_Space varchar(50)  
)  
--Create Stored Procedure String  
SELECT @cmdstr = 'sp_msforeachtable ''sp_spaceused "?"''' 
--Populate Tempoary Table  
INSERT INTO #TempTable EXEC(@cmdstr)  
--Determine sorting method  
SELECT * FROM #TempTable ORDER BY Table_Name  
--Delete Temporay Table  
DROP TABLE #TempTable  
END 
 

3.清除指定DB的事务日志。开发过程中我们把DB的日志搞得很大

BACKUP log [myDatabase] with truncate_only  
go  
DBCC SHRINKDATABASE ([myDatabase], 10, TRUNCATEONLY)  
go 

 

当然另一个好主意是要备份它们:

BACKUP  
LOG [myDatabase] TO DISK = N'C:\Backups\myDatabase_log.trn' WITH 
NOFORMAT, NOINIT, NAME = N'myDatabase_log', SKIP, REWIND, NOUNLOAD,  
STATS = 10 
 

4.列出DB中表的数量:

USE YOURDBNAME  
SELECT COUNT(*) from information_schema.tables  
WHERE table_type = 'base table' 


5.按当前时期备份DataBase,你可以用它当做JOB来执行。

DECLARE @currentday varchar(10)  
set @currentday = datepart(day,getdate())  
IF LEN(@currentday) = 1  
BEGIN 
    SET @currentday = '0' + @currentday  
END 
DECLARE @currentmonth varchar(10)  
SET @currentmOnth= datepart(month,getdate())  
IF LEN(@currentmonth) = 1  
BEGIN 
    SET @currentmOnth= '0' + @currentmonth  
END 
DECLARE @currentyear varchar(10)  
SET @currentyear = datepart(year,getdate())  
DECLARE @fileName varchar(100)  
SET @fileName = 'D:\dbbackup\' + @currentyear  
+ '_'    + @currentmonth  + '_' + @currentday  + '.bak' 
BACKUP DATABASE yourdatabase TO DISK = @fileName WITH NOFORMAT, INIT,  
NAME = N'myDatabase -Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10  
GO 



Author : Petter Liu     http://wintersun.cnblogs.com

希望对您有帮助。


推荐阅读
author-avatar
小小的dream
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有