Tuesday, March 8, 2011

Understand SQL Server Architecture

Whenever we need info for Edition we need to blow following query to to check edition. Do you know, what does it mean

SELECT SERVERPROPERTY('Edition');

There is also a server property called EngineEdition that you can inspect, as follows:

SELECT SERVERPROPERTY('EngineEdition');

Return values

  1. is not a possible value
  2. Standard or Workgroup,
  3. indicates that your SQL Server edition is either Enterprise, Enterprise Evaluation, or Developer
  4. Express Edition
Before go in depth of SQL Server Engine we need to recall some of the object, we do in day to day DBA Role

SQL Server 2008, there are three types of system metadata objects

  1. Dynamic Management Objects- It’s don’t really correspond to physical tables—they contain information gathered from internal structures to allow you to observe the current state of your SQL Server instance

Pseudotables are tables that are not based on data stored on disk but are built as needed from internal structures and can be queried exactly as if they are tables. Like sysprocesses and syscacheobjects

All the catalog views (as well as the Dynamic Management Objects and compatibility views) are in the sys schema, and you must reference the schema name when you access the objects.

definition of sys.tables

SELECT object_definition (object_id('sys.tables'));

System Functions

  • SERVERPROPERTY
  • COLUMNPROPERTY
  • DATABASEPROPERTY
  • DATABASEPROPERTYEX
  • INDEXPROPERTY
  • INDEXKEY_PROPERTY
  • OBJECTPROPERTY
  • OBJECTPROPERTYEX
  • SQL_VARIANT_PROPERTY
  • FILEPROPERTY
  • FILEGROUPPROPERTY
  • TYPEPROPERTY
  • CONNECTIONPROPERTY
  • ASSEMBLYPROPERTY

i.e SELECT DATABASEPROPERTYEX('msdb', 'Recovery');

To view the recovery models of all our databases, you can use the sys.databases view:

SELECT name, recovery_model, recovery_model_desc FROM sys.databases;

T o find out the database ID

SELECT database_id FROM sys.databases WHERE name = 'AdventureWorks2008';

By Function

SELECT DB_ID('AdventureWorks2008');

The Major Component of SQL Server Engine

As you can see that Protocol layer is the upper most layer, which receive the request and translate it into a form that the relational database can understand and it return the result in a form that a client can understand.

For TSQL, the relational Engine parse, compile and optimizes the request. As a batch executed, if the data is needed, a request sent to storage Engine. The storage Engine Manage all data access, bulk insert and certain DBCC command..

SQLOS Layer handle s the activities that are normally consider to be operating system responsibility such as thread management, synchronize primitives, deadlock detection, memory management including buffer pool.

Sunday, October 31, 2010

SP to find the Drive Space,free and percentage Using T-SQL


use master

go

CREATE PROCEDURE sp_diskspace

AS

SET NOCOUNT ON

DECLARE @hr int

DECLARE @fso int

DECLARE @drive char(1)

DECLARE @odrive int

DECLARE @TotalSize varchar(20)

DECLARE @MB bigint ; SET @MB = 1048576

CREATE TABLE #drives (drive char(1) PRIMARY KEY,

FreeSpace int NULL,

TotalSize int NULL)

INSERT #drives(drive,FreeSpace)

EXEC master.dbo.xp_fixeddrives

EXEC @hr=sp_OACreate 'Scripting.FileSystemObject',@fso OUT

IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

DECLARE dcur CURSOR LOCAL FAST_FORWARD

FOR SELECT drive from #drives

ORDER by drive

OPEN dcur

FETCH NEXT FROM dcur INTO @drive

WHILE @@FETCH_STATUS=0

BEGIN

EXEC @hr = sp_OAMethod @fso,'GetDrive', @odrive OUT, @drive

IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

EXEC @hr = sp_OAGetProperty @odrive,'TotalSize', @TotalSize OUT

IF @hr <> 0 EXEC sp_OAGetErrorInfo @odrive

UPDATE #drives

SET TotalSize=@TotalSize/@MB

WHERE drive=@drive

FETCH NEXT FROM dcur INTO @drive

END

CLOSE dcur

DEALLOCATE dcur

EXEC @hr=sp_OADestroy @fso

IF @hr <> 0 EXEC sp_OAGetErrorInfo @fso

SELECT drive,

FreeSpace as 'Free(MB)',

TotalSize as 'Total(MB)',

CAST((FreeSpace/(TotalSize*1.0))*100.0 as int) as 'Free(%)'

FROM #drives

ORDER BY drive

DROP TABLE #drives

RETURN

go


You will find output like


Grant Execute Permission on all SP for a database

Following method can be used to create statement to grant Execute permission on all SP for a Database.

Use DatabaseName

select 'Grant Execute on [' + name + '] to [LoginName]'
from sysobjects where xtype in ('P')

Create a user/assign role for a Single Database

We DBA have a great responsibility to avoid access to unauthorized access to users. So we can give access to users for Required Databases only. Following are the method to create/assign used for a single DB.

USE [DatabaseName]
GO

CREATE USER [LoginName] FOR LOGIN [LoginName]
GO

USE [DatabaseName]
GO

ALTER USER [LoginName] WITH DEFAULT_SCHEMA=[dbo]
GO

USE [DatabaseName]
GO

EXEC sp_addrolemember N'db_owner', N'LoginName'
GO

Rename Database from T-SQL

Rename Database

Sometime we rename database as per business Logic.

USE master

ALTER DATABASE DatabaseName

SET single_user

GO

ALTER DATABASE DatabaseName

MODIFY NAME = NewDatabaseName

GO

USE master

ALTER DATABASE NewDatabaseName

SET multi_user

GO

Backup & Restore from TSQL

Database Backup and Restore from TSQL

For Native Backup

Database MYDatabase has full backup DatabaseName.bak. The database can be restored using following two steps.


Step 1: Retrive the Logical file name of the database from backup.

RESTORE FILELISTONLY
FROM DISK = 'D:\Backup\DatabaseName.bak'
GO

Step 2: Use the values in the LogicalName Column in following Step.
ALTER DATABASE YourDB
SET SINGLE_USER WITH
ROLLBACK IMMEDIATE

----Restore Database
RESTORE DATABASE MYDatabase
FROM DISK = 'D:\Backup\DatabaseName.bak'
WITH MOVE 'MDF_LogicalName' TO 'D:\MSSQL\Data\DBFileName_Data.mdf',
MOVE 'LDF_LogicalName' TO 'D:\MSSQL\Log\DBFileName_Log.ldf'

ALTER DATABASE YourDB SET MULTI_USER
GO

To backup database

Backup database Database_Name to Disk='D:\Backup\DatabaseName.bak' with stats=10
===============================================================
For LiteSpeed

--To Check the logical name of the file

exec master.dbo.xp_restore_filelistonly @filename = 'path of the database backup.bak'

i.e logical name like- Database_Data, Database_Log

--To Find the path where mdf and ndf resides for the said database.

--select * from sysaltfiles

sp_helpdb 'DatabaseName'

--To Restore database from given backup file

exec master.dbo.xp_restore_database @database = N'DatabaseName',

@filename = N'path of the database backup.bak',

@with = N'RECOVERY', @with = N'NOUNLOAD', @with = N'STATS = 10',

@with = N'MOVE N'' Database_Data '' TO N''N:\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\DatabaseName.mdf''',

@with = N'MOVE N'' Database_Log '' TO N''K:\Microsoft SQL Server\MSSQL\Logs\ DatabaseName.ldf'''

===============================================================
For SQL Safe

Backup Database

exec master..xp_ss_backup

@database = 'DatabaseName', @filename = 'D:\Backup\DatabaseName_FUll_Date.safe', @init = 1
, @compressionlevel = 'isize', @threads = 3

To verify backup file
xp_ss_listfiles @filename='D:\DB_Backup\DatabaseName_FUll_Date.safe'

Restore Database

exec master..xp_ss_restore
@database = 'Database_Name',
@filename='D:\DB_Backup\DatabaseName_FUll_Date.safe',
@withmove = 'DB_MDF_LOgicalName D:\MS SQL Server\Data\DBName.mdf'
,@withmove = 'DB_LDF_logicalName_Log F:\MS SQL Server\Logs\DBName.ldf'
,@withmove = 'DB_LDF_logicalName_Log1 F:\MS SQL Server\Logs\DBName1.ldf'
,@withmove = 'DB_Catalog_FT E:\MS SQL Server\FText\DB_Catalog_Production_FT'
,@replace = 1
==================================================================
Below are method to find orphan User and Way to fix it
--To Verify User SID matches system SID

sp_change_users_login 'report'

--If you find any Orphen user with SYSTEM SID, then we can fix with Following Command

sp_change_users_login 'update_one','username','username'

==================================================================
Query to find out Estimated Time, Percentage, Elapsed time of a RESTORE DATABASE/BACKUP DATABASE

SELECT r.session_id ,r.command,CONVERT(NUMERIC(6,2),r.percent_complete)AS [Percent Complete],CONVERT(VARCHAR(20),DATEADD(ms,r.estimated_completion_time,GetDate()),20) AS [ETA Completion Time],CONVERT(NUMERIC(10,2),r.total_elapsed_time/1000.0/60.0) AS [Elapsed Min],CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0) AS [ETA Min],CONVERT(NUMERIC(10,2),r.estimated_completion_time/1000.0/60.0/60.0) AS [ETA Hours]

,CONVERT(VARCHAR(1000),(SELECT SUBSTRING(text,r.statement_start_offset/2

,CASE WHEN r.statement_end_offset = -1 THEN 1000 ELSE (r.statement_end_offset-r.statement_start_offset)/2 END)

FROM sys.dm_exec_sql_text(sql_handle)))FROM sys.dm_exec_requests r

WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE')



Sunday, May 23, 2010

Move master database from one drive to another

Sometime you may need to move master database from one drive then you may help from given below info

Open SQL Server Configuration manager from program files. In SQL Services Nodes, right clieck on SQL Server(i.e.MSSQLSERVER) and choose Properties and go to Advanced TAB and Edit Startup Parameters values to point to planned location for the master database data abd log files and then click on ok.

The parameter value for the data file must follow the -d parameter and the value for the log file must follow the -l parameter. The following example shows the parameter values for the default location of the master data and log files.

-dC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\
master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\
LOG\ERRORLOG;-lC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\
DATA\mastlog.ldf


If the planned relocation for the master data and log files is E:\SQLData, the parameter values would be changed as follows:

-dE:\SQLData\master.mdf;-eC:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\LOG\ERRORLOG;-lE:\SQLData\mastlog.ldf

stop the instance by right click and choose stop and move the master.mdf and master.ldf to new location.

and restart the instance.

Verify the file change for the master database by running the following query.

CopySELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID('master');
GO