Sql Server實用操作小技巧集合
包括安裝時提示有掛起的操作
(一) 掛起操作
(二)
在安裝Sql或sp補丁的時候系統提示之前有掛起的安裝操作
到HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager
刪除PendingFileRenameOperations
(二)收縮數據庫
DBCC REINDEX
DBCC INDEXDEFRAG
DBCC SHRINKDB
DBCC SHRINKFILE
(三) 壓縮數據庫
dbcc shrinkdatabase(dbname)
(四)轉移數據庫給新用戶以已存在用戶權限
exec sp_change_users_login
go
(五)檢查備份集
RESTORE VERIFYONLY from disk=
(六)修復數據庫
ALTER DATABASE [dvbbs] SET SINGLE_USER
GO
DBCC CHECKDB(
GO
ALTER DATABASE [dvbbs] SET MULTI_USER
GO
SQL SERVER日志清除的兩種方法
在使用過程中大家經常碰到數據庫日志非常大的情況
方法一
一般情況下
方法二
SET NOCOUNT ON
DECLARE @LogicalFileName sysname
@MaxMinutes INT
@NewSize INT
USE tablename
SELECT @LogicalFileName =
@MaxMinutes =
@NewSize =
DECLARE @OriginalSize int
SELECT @OriginalSize = size
FROM sysfiles
WHERE name = @LogicalFileName
SELECT
CONVERT(VARCHAR(
CONVERT(VARCHAR(
FROM sysfiles
WHERE name = @LogicalFileName
CREATE TABLE DummyTrans
(DummyColumn char (
DECLARE @Counter INT
@StartTime DATETIME
@TruncLog VARCHAR(
SELECT @StartTime = GETDATE()
@TruncLog =
DBCC SHRINKFILE (@LogicalFileName
EXEC (@TruncLog)
WHILE @MaxMinutes > DATEDIFF (mi
AND @OriginalSize = (SELECT size FROM sysfiles WHERE name = @LogicalFileName)
AND (@OriginalSize *
BEGIN
SELECT @Counter =
WHILE ((@Counter < @OriginalSize /
BEGIN
INSERT DummyTrans VALUES (
DELETE DummyTrans
SELECT @Counter = @Counter +
END
EXEC (@TruncLog)
END
SELECT
CONVERT(VARCHAR(
CONVERT(VARCHAR(
FROM sysfiles
WHERE name = @LogicalFileName
DROP TABLE DummyTrans
SET NOCOUNT OFF
刪除數據庫中重復數據的幾個方法
數據庫的使用過程中由於程序方面的問題有時候會碰到重復數據
方法一
declare @max integer
declare cur_rows cursor local for select 主字段
open cur_rows
fetch cur_rows into @id
while @@fetch_status=
begin
select @max = @max
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id
end
close cur_rows
set rowcount
方法二
有兩個意義上的重復記錄
select distinct * from tableName
就可以得到無重復記錄的結果集
如果該表需要刪除重復的記錄(重復記錄保留
select distinct * into #Tmp from tableName
drop table tableName
select * into tableName from #Tmp
drop table #Tmp
發生這種重復的原因是表設計不周產生的
假設有重復的字段為Name
select identity(int
select min(autoID) as autoID into #Tmp
select * from #Tmp where autoID in(select autoID from #tmp
最後一個select即得到了Name
更改數據庫中表的所屬用戶的兩個方法
大家可能會經常碰到一個數據庫備份還原到另外一台機器結果導致所有的表都不能打開了
exec sp_changeobjectowner
CREATE PROCEDURE dbo
@OldOwner as NVARCHAR(
@NewOwner as NVARCHAR(
AS
DECLARE @Name as NVARCHAR(
DECLARE @Owner as NVARCHAR(
DECLARE @OwnerName as NVARCHAR(
DECLARE curObject CURSOR FOR
select
from sysobjects
where user_name(uid)=@OldOwner
order by name
OPEN curObject
FETCH NEXT FROM curObject INTO @Name
WHILE(@@FETCH_STATUS=
BEGIN
if @Owner=@OldOwner
begin
set @OwnerName = @OldOwner +
exec sp_changeobjectowner @OwnerName
end
FETCH NEXT FROM curObject INTO @Name
END
close curObject
deallocate curObject
GO
SQL SERVER中直接循環寫入數據
沒什麼好說的了
declare @i int
set @i=
while @i<
begin
insert into test (userid) values(@i)
set @i=@i+
end
無數據庫日志文件恢復數據庫方法兩則
數據庫日志文件的誤刪或別的原因引起數據庫日志的損壞
From:http://tw.wingwit.com/Article/program/SQLServer/201311/22164.html