RSS

Category Archives: Administration

How to Change the Default Database Location

Problem :

After I Create Cluster and I make 2 Share Disk one for Data and the another for Logs I forget to Customize the location For the database What can I do to Change this Location ?

Salutation : 

You have two ways the first by T-SQL and the Second is Wizard Steps :

First Way:

A- Change the Default location for data file :

EXEC xp_instance_regwrite

N’HKEY_LOCAL_MACHINE’,

N’Software\Microsoft\MSSQLServer\MSSQLServer’,

N’DefaultData’,

REG_SZ

,N’F:\MSSQL10_50.MSSQLSERVER\MSSQL\DATA’

GO

B- Change the Default location for Logs file :

EXEC xp_instance_regwrite

N’HKEY_LOCAL_MACHINE’,

N’Software\Microsoft\MSSQLServer\MSSQLServer’,

N’DefaultLog’,

REG_SZ

,N’G:\MSSQL10_50.MSSQLSERVER\MSSQL\Log’

GO

Second Way:

Open the management Studio >>> Write Click on the Server >>> Select properties

Change1

Then Select Database Setting >>> you Will See Database Default Location

Change2

 

Tags:

TRY…CATCH and ERROR Handling

CREATE TABLE TPA
(ID  INT , [NAME]  NVARCHAR(50))
GO
INSERT TPA VALUES (1,’MOSTAFA’)
INSERT TPA VALUES (2,’ELMASRY’)

BEGIN TRY
— Generate a divide-by-zero error.
SELECT ID+[NAME] FROM TPA
END TRY
BEGIN CATCH
SELECT * FROM TPA
END CATCH;
GO

BEGIN TRY
— Generate a divide-by-zero error.
SELECT ID+[NAME] FROM TPA
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber,
ERROR_SEVERITY() AS ErrorSeverity,
ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure,
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
GO

 
Leave a comment

Posted by on February 15, 2012 in Administration, Errors

 

Repairing Suspect SQL Database

Before you run this script

  • Kill all connections and stop SQL Server
  • Perform a Checkdisk with repair option
  • Perform a Defragmentation
  • Now copy the files necessary (MDF, LDF and Backups)
  • Perform a backup
  • Restore the backup
  • Repair the Database (DBCC CHECKDB)
  • Backup the repaired DB

USE [master]
GO
ALTER DATABASE <dbname> SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
ALTER DATABASE <dbname> SET SINGLE_USER
GO
DBCC CHECKDB <dbname>, REPAIR_REBUILD) WITH ALL_ERRORMSGS, NO_INFOMSGS
GO
ALTER DATABASE <dbname> SET MULTI_USER
GO

Or

Take Care From this Script becouse it will make repaire and may be some Data will loss

EXEC sp_resetstatus ‘yourDBname’;
ALTER DATABASE yourDBname SET EMERGENCY
DBCC checkdb(‘yourDBname’)
ALTER DATABASE yourDBname SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB (‘yourDBname’, REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE yourDBname SET MULTI_USER

 
2 Comments

Posted by on February 14, 2012 in Administration, Errors

 

How to remove Instance or Feature from SQL Server

I do this steps in my SQL Server 2012 and you can make this steps in Any version like 2005 – 2008 – 2008 R2 Also To remove or Add or repaire SQL Server :

1- Go to Programe and Feature

2- Select your SQL Server name

3- Write click on the name and select Uninstall

4- If you want to add New instance or to add New feature to exsiting instance select Add , Also if you want to repair your instance select the Second Choice Repair

5- in this example we will select Remove

5- After this step we will select the instance you want to remove it or you want to remove some feature from this instance

6- After this step clic Next to determine if you want to remove the instance of the whole or to remove Feature from this insance if you want to remove the instance sellect all thisng in the Screen , Else select the feature you want to be remove it .

7- After you determine  waht you Need . make Next to make SQL Sever Check your role may be if you reomve this instance SQL Server will give you Error or Warning so this step is very imporatnt

8- Then Click Next to tell SQL Sever you are Arealdy to remove your Selected

9- after this step if you click Next SQL Server will reove your Selected so i think you must be Retreat yourself becouse the Next step is final {There is no room to return} if you want Click next if you Retreated  yourself  click cansel.

sorry i cant complete with you the final Step becouse i Retreated  my self and i discovered i love Microsoft and i cant reove any tool from microsoft so Complete this step Alone

Good Luck

best Regardes

Mostafa Elmasry

 

Delete file on your PC by SQL Server

you must be in the first Configure SQl server to allow you to make this operation so Run this script on your server (take it from this link)

[https://mostafaelmasry.wordpress.com/2012/01/20/ole-automation-procedures-to-delete-file-from-pc/]

then run this Script

DECLARE @Result int

declare @File_Location as nvarchar(300) = ‘F:\fff.txt’

DECLARE @FSO_Token int

EXEC @Result = sp_OACreate ‘Scripting.FileSystemObject’, @FSO_Token OUTPUT

EXEC @Result = sp_OAMethod @FSO_Token, ‘DeleteFile’, NULL, @File_Location

EXEC @Result = sp_OADestroy @FSO_Token

 

 

 

 

Stored Procedure Restore From All Files In Directory

When i search in the internet i  see Stored procedure make restore from all files in directory i read it in the first then i take this Sp and make edit on it to customize it and add New paramter to make anather thing if you want to the source for this Sp go to this link

http://www.karaszi.com/SQLServer/code/sp_RestoreFromAllFilesInDirectory_2008sp1.txt

/*

Customized By Mostafa Elmasry

Dwenload Sp To SQL 2012: http://hotfile.com/dl/142851801/0d8e1c7/SP_Restore_Dynamic.sql.html

Dwenload  SP to SQL 2005 : http://hotfile.com/dl/143006210/7b26c20/SP_Restore_Dynamic_to_SQL_2005.sql.html

This Stored Procedure use to Restore All file backup From @SourceDirBackupFiles

its update to work on SQL 2012 but if you run this script on this version must be Add this column [Containment] in the #bdev table in the last i add it

but i make this column is Uncommite . It’s Work very good on all version 2000, 2005, 2008, 2008R2 + 2012 (but don’t forget make Commentto the Column Containment in #bdev Table)

to Exec this Sp must be give it 5 paramter

@SourceDirBackupFiles = Your backup file location

@DestDirDbFiles       = database file location MDF will creat on this path

@DestDirLogFiles      = database Log_File location lDF will creat on this path

@Mode_Restore         = 0 >> the database name will be = Logicalname , 1 >> Tha database name will be the  = same backup name

@Exce_Command      = 0 >> the Sp will Exec the Command restore    , 1 >> The SP will print the comand and don’t make exec

it dont make overwite

IF the backup have more than backup in one file this code make restore to the max position

Restores from all files in a certain directory

Sample execution:

EXEC sp_RestoreFromAllFilesInDirectory

@SourceDirBackupFiles = ‘E:\DataBase\Backup\’,

@DestDirDbFiles       = ‘E:\DataBase\R\’ ,

@DestDirLogFiles      = ‘E:\DataBase\R\’ ,

@Mode_Restore         =  1    ,

@Exce_Command         = 0

*/

USE master

GO

/****** Object:  StoredProcedure [dbo].[sp_RestoreFromAllFilesInDirectory]    Script Date: 04/01/2010 06:08:31 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

Create proc [dbo].[sp_RestoreFromAllFilesInDirectory]

(

@SourceDirBackupFiles NVARCHAR(200) ,

@DestDirDbFiles NVARCHAR(200)       ,

@DestDirLogFiles NVARCHAR(200)      ,

@Mode_Restore int                   ,

@Exce_Command int

)

AS

begin transaction

SET NOCOUNT ON

–Table to hold each backup file name in

CREATE TABLE #files(fname VARCHAR(200),depth INT, file_ INT)

INSERT #files

EXECUTE master.dbo.xp_dirtree @SourceDirBackupFiles, 1, 1

–Table to hold the result from RESTORE HEADERONLY. Needed to get the database name out from

CREATE TABLE #bdev(

BackupName NVARCHAR(300)

,BackupDescription NVARCHAR(255)

,BackupType smallint

,ExpirationDate datetime

,Compressed tinyint

,Position smallint

,DeviceType tinyint

,UserName NVARCHAR(128)

,ServerName NVARCHAR(128)

,DatabaseName NVARCHAR(128)

,DatabaseVersion INT

,DatabaseCreationDate datetime

,BackupSize numeric(20,0)

,FirstLSN numeric(30,0)

,LastLSN numeric(30,0)

,CheckpointLSN numeric(30,0)

,DatabaseBackupLSN numeric(30,0)

,BackupStartDate datetime

,BackupFinishDate datetime

,SortOrder smallint

,[CodePage] smallint

,UnicodeLocaleId INT

,UnicodeComparisonStyle INT

,CompatibilityLevel tinyint

,SoftwareVendorId INT

,SoftwareVersionMajor INT

,SoftwareVersionMinor INT

,SoftwareVersionBuild INT

,MachineName NVARCHAR(128)

,Flags INT

,BindingID uniqueidentifier

,RecoveryForkID uniqueidentifier

,Collation NVARCHAR(128)

,FamilyGUID uniqueidentifier

,HasBulkLoggedData INT

,IsSnapshot INT

,IsReadOnly INT

,IsSingleUser INT

,HasBackupChecksums INT

,IsDamaged INT

,BegibsLogChain INT

,HasIncompleteMetaData INT

,IsForceOffline INT

,IsCopyOnly INT

,FirstRecoveryForkID uniqueidentifier

,ForkPointLSN numeric(25,0)

,RecoveryModel NVARCHAR(128)

,DifferentialBaseLSN numeric(25,0)

,DifferentialBaseGUID uniqueidentifier

,BackupTypeDescription NVARCHAR(128)

,BackupSetGUID uniqueidentifier

,CompressedBackupSize NVARCHAR(128)

,Containment int ———————– if you use SQl 2012 Enable this Column

)

–Table to hold result from RESTORE FILELISTONLY. Need to generate the MOVE options to the RESTORE command

CREATE TABLE #dbfiles(

LogicalName NVARCHAR(128)

,PhysicalName NVARCHAR(260)

,Type CHAR(1)

,FileGroupName NVARCHAR(128)

,Size numeric(20,0)

,MaxSize numeric(20,0)

,FileId INT

,CreateLSN numeric(25,0)

,DropLSN numeric(25,0)

,UniqueId uniqueidentifier

,ReadOnlyLSN numeric(25,0)

,ReadWriteLSN numeric(25,0)

,BackupSizeInBytes INT

,SourceBlockSize INT

,FilegroupId INT

,LogGroupGUID uniqueidentifier

,DifferentialBaseLSN numeric(25)

,DifferentialBaseGUID uniqueidentifier

,IsReadOnly INT

,IsPresent INT

,TDEThumbprint NVARCHAR(128)

)

DECLARE @fname VARCHAR(200)

DECLARE @FNAME_RESTORE NVARCHAR(200)

DECLARE @dirfile VARCHAR(300)

DECLARE @LogicalName NVARCHAR(128)

DECLARE @PhysicalName NVARCHAR(260)

DECLARE @type CHAR(1)

DECLARE @DbName sysname

DECLARE @sql NVARCHAR(1000)

Declare @position int

—Check Mode_Reestore IF @Mode_Restore = 0 [Database Name will be = The Logical_name] ElseIF @mode_Restore = 0 [Database Name Will be = The backup Name] Else [Error massage]

DECLARE files CURSOR FOR

–SELECT FNAME FROM #files

select FNAME,left (fname,case charindex(‘.’,fname) when 0 then   len(fname)   else    charindex(‘.’,fname) -1   end)from #files

DECLARE dbfiles CURSOR FOR

SELECT LogicalName, PhysicalName, Type FROM #dbfiles

OPEN files

FETCH NEXT FROM files INTO @fname , @FNAME_RESTORE

WHILE @@FETCH_STATUS = 0

BEGIN

SET @dirfile = @SourceDirBackupFiles + @fname

–Get database name from RESTORE HEADERONLY, assumes there’s only one backup on each backup file.

TRUNCATE TABLE #bdev

INSERT #bdev

EXEC(‘RESTORE HEADERONLY FROM DISK = ”’ + @dirfile + ””)

set @position = (select max(position) from #bdev)

SET @DbName = (SELECT DatabaseName FROM #bdev where position = @position)

if @Mode_Restore = 1

begin

–Construct the beginning for the RESTORE DATABASE command

SET @sql = ‘RESTORE DATABASE ‘ + @FNAME_RESTORE + ‘ FROM DISK = ”’ + @dirfile + ”’ WITH MOVE ‘

end

Else If @Mode_Restore = 0

begin

–Construct the beginning for the RESTORE DATABASE command

SET @sql = ‘RESTORE DATABASE ‘ + @DbName + ‘ FROM DISK = ”’ + @dirfile + ”’ WITH MOVE ‘

end

else

BEGIN

— Rollback the transaction

ROLLBACK

— Raise an error and return

RAISERROR (‘Must be @mode_restore = 1 or o.’, 16, 1)

RETURN

end

–Get information about database files from backup device into temp table

TRUNCATE TABLE #dbfiles

INSERT #dbfiles

EXEC(‘RESTORE FILELISTONLY FROM DISK = ”’ + @dirfile + ””)

OPEN dbfiles

FETCH NEXT FROM dbfiles INTO @LogicalName, @PhysicalName, @type

–For each database file that the database uses

WHILE @@FETCH_STATUS = 0

BEGIN

IF @type = ‘D’

SET @sql = @sql + ”” + @LogicalName + ”’ TO ”’ + @DestDirDbFiles + @LogicalName  + ‘.mdf”, MOVE ‘

ELSE IF @type = ‘L’

SET @sql = @sql + ”” + @LogicalName + ”’ TO ”’ + @DestDirLogFiles + @LogicalName  + ‘.ldf”’

FETCH NEXT FROM dbfiles INTO @LogicalName, @PhysicalName, @type

END

If @Exce_Command = 1

begin

EXEC(@sql)

end

Else IF @Exce_Command = 0

begin

–Here’s the actual RESTORE command

PRINT @sql

End

Else

BEGIN

— Rollback the transaction

ROLLBACK

— Raise an error and return

RAISERROR (‘Must be @Exce_Command = 1 or o.’, 16, 1)

RETURN

end

CLOSE dbfiles

FETCH NEXT FROM files INTO @fname , @FNAME_RESTORE

IF @@ERROR <> 0

BEGIN

— Rollback the transaction

ROLLBACK

— Raise an error and return

RAISERROR (‘Error in restoring the File’, 16, 1)

RETURN

END

END

COMMIT

CLOSE files

DEALLOCATE dbfiles

DEALLOCATE files

 

Returen All File in Any Directory Stored Procedure Sp_ListFiles

USE master

GO

CREATE PROCEDURE dbo.sp_ListFiles

@PCWrite varchar(2000),

@DBTable varchar(100)= NULL,

@PCIntra varchar(100)= NULL,

@PCExtra varchar(100)= NULL,

@DBUltra bit = 0

AS

SET NOCOUNT ON

DECLARE @Return int

DECLARE @Retain int

DECLARE @Status int

SET @Status = 0

DECLARE @Task varchar(2000)

DECLARE @Work varchar(2000)

DECLARE @Wish varchar(2000)

SET @Work = ‘DIR ‘ + ‘”‘ + @PCWrite + ‘”‘

CREATE TABLE #DBAZ (Name varchar(400), Work int IDENTITY(1,1))

INSERT #DBAZ EXECUTE @Return = master.dbo.xp_cmdshell @Work

SET @Retain = @@ERROR

IF @Status = 0 SET @Status = @Retain

IF @Status = 0 SET @Status = @Return

IF (SELECT COUNT(*) FROM #DBAZ) < 4

BEGIN

SELECT @Wish = Name FROM #DBAZ WHERE Work = 1

IF @Wish IS NULL

BEGIN

RAISERROR (‘General error [%d]’,16,1,@Status)

END

ELSE

BEGIN

RAISERROR (@Wish,16,1)

END

END

ELSE

BEGIN

DELETE #DBAZ WHERE ISDATE(SUBSTRING(Name,1,10)) = 0 OR SUBSTRING

(Name,40,1) = ‘.’ OR Name LIKE ‘%.lnk’

IF @DBTable IS NULL

BEGIN

SELECT SUBSTRING(Name,40,100) AS Files

FROM #DBAZ

WHERE 0 = 0

AND (@DBUltra = 0 OR Name LIKE ‘% %’)

AND (@DBUltra != 0 OR Name NOT LIKE ‘% %’)

AND (@PCIntra IS NULL OR SUBSTRING(Name,40,100) LIKE @PCIntra)

AND (@PCExtra IS NULL OR SUBSTRING(Name,40,100) NOT LIKE @PCExtra)

ORDER BY 1

END

ELSE

BEGIN

SET @Task = ‘ INSERT ‘ + REPLACE(@DBTable,CHAR(32),CHAR(95))

+ ‘ SELECT SUBSTRING(Name,40,100) AS Files’

+ ‘ FROM #DBAZ’

+ ‘ WHERE 0 = 0’

+ CASE WHEN @DBUltra = 0 THEN ” ELSE ‘ AND Name LIKE ‘ + CHAR(39) + ‘% %’ + CHAR(39) END

+ CASE WHEN @DBUltra != 0 THEN ” ELSE ‘ AND Name NOT LIKE ‘ + CHAR(39) + ‘% %’ + CHAR(39) END

+ CASE WHEN @PCIntra IS NULL THEN ” ELSE ‘ AND SUBSTRING (Name,40,100) LIKE ‘ + CHAR(39) + @PCIntra + CHAR(39) END

+ CASE WHEN @PCExtra IS NULL THEN ” ELSE ‘ AND SUBSTRING

(Name,40,100) NOT LIKE ‘ + CHAR(39) + @PCExtra + CHAR(39) END

+ ‘ ORDER BY 1’

IF @Status = 0 EXECUTE (@Task) SET @Return = @@ERROR

IF @Status = 0 SET @Status = @Return

END

END

DROP TABLE #DBAZ

SET NOCOUNT OFF

RETURN (@Status)

GO

—-EXECUTE sp_ListFiles ‘E:\DataBase’,NULL,NULL,NULL,1