Friday 22 November 2013

SQL Server : T-SQL command that will determine in which filegroup, a particular table exist

It is very common to deal with situation where you have thousands of tables which are residing on multiple filegroups and you would like to know that in which filegroup, a particular table exist in your database.

Please change database table name accordingly.

**********************************************


/*Script for finding on which Filegroup the object resides in a database*/

USE Test
GO
SELECT object_name(i.[object_id]) as Name_of_Object,
i.name as Index_Name,
i.type_desc as Index_Type,
f.name as Name_of_Filegroup,
a.type as Object_Type,
f.type,
f.type_desc
FROM sys.filegroups as f
INNER JOIN sys.indexes as i
 ON f.data_space_id = i.data_space_id
INNER JOIN sys.all_objects as a
 ON i.object_id = a.object_id
WHERE a.type ='U' -- User defined tables only
AND object_name(i.[object_id]) ='employee' -- Specific object

GO

Hope it will help you .

Brgds,

Chhavinath Mishra
Sr. Database Administrator

Microsoft Certified IT Professional (MCITP)

SQL Server : Sample Scripts to create database, table & Index

It is very common to deal with situation where you have to create database and tables using T-SQL.

Here are the sample scripts for same which can be used as reference.


First check the data and log file location for any database if there is:
  
Use YourExistingDB
go
sp_helpfile

-- Create Dabase

use master
go
create database Test
on Primary (Name = test_data1, FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012B\MSSQL\DATA\test_data1.mdf'),
Filegroup Test_Secondary
(Name = test_Data_2, FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012B\MSSQL\DATA\test_Data_2.ndf'),
Filegroup Test_Archive
(Name = test_data3 , FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012B\MSSQL\DATA\test_data2.ndf')
Log ON (Name = Test_Log, FileName = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQL2012B\MSSQL\Log\test_log.ldf')
Go

-- Create Table

use Test
Go
Create Table dbo.Employee
(emp_id int,
emp_fname varchar (20),
emp_lname varchar (30))
on test_secondary
go

-- Create Index


use Test
Go
Create clustered index CIX_emp_Id on Test.dbo.Employee (emp_id)

Hope it will help you.

Brgds,

Chhavinath Mishra
Sr. Database Administrator
Microsoft Certified IT Professional (MCITP)

Thursday 21 November 2013

SQL Server : T-SQL command that will determine if a table exist or not

It is very common to deal with situation where you have thousands of tables and you would like to know that whether a particular table exist or not in your database.T-SQL command that will determine if a table exist or not. 

Please change database name and table name accordingly.

**********************************************

IF EXISTS
(SELECT *
FROM YourDB.INFORMATION_SCHEMA.TABLES
WHERE
TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'YourTable'
AND TABLE_TYPE = 'BASE TABLE'
)
PRINT ' Table Exist'
Else
PRINT ' Table Does not Exist'
GO

**********************************************

Hope it will help you .

Brgds,

Chhavinath Mishra
Sr. Database Administrator


Microsoft Certified IT Professional (MCITP)

Tuesday 29 October 2013

SQL SERVER – Wait Types

When I was working with couple of frequent blocking issue in our production servers, I have noticed different types of wait resources which are very common and can be very useful but people often overlooked these while troubleshooting. I also feel that "wait stats" is one of the most under-utilized performance troubleshooting methodologies in the SQL Server.

Any time a user connection is waiting, SQL Server keep track of wait time. For example, the application requests resources such as I/O, locks, or memory and can wait for the resource to be available.

There are few system wait types which are always present and there are a few wait types which can really cause a heavy bottleneck for your system.


Types of Waits

As per BOL, there are three types of wait types, namely:

Resource waits
Resource waits occur when a worker requests access to a resource that is not available because the resource is being used by some other worker or is not yet available. Examples of resource waits are locks, latches, network and disk I/O waits. Lock and latch waits are waits on synchronization objects
Queue waits
Queue waits occur when a worker is idle, waiting for work to be assigned. Queue waits are most typically seen with system background tasks such as the deadlock monitor and deleted record cleanup tasks. These tasks will wait for work requests to be placed into a work queue. Queue waits may also periodically become active even if no new packets have been put on the queue.
External waits
External waits occur when a SQL Server worker is waiting for an external event, such as an extended stored procedure call or a linked server query, to finish. When you diagnose blocking issues, remember that external waits do not always imply that the worker is idle, because the worker may actively be running some external code.

To check the wait types for any server, just run the following simple T-SQL:
SELECT * FROM sys.dm_os_wait_stats

Along with above thoughts , it woold be good to extract useful information from below T-SQL. This will show the waits grouped together as a percentage of all waits on the system, in decreasing order. The waits to be concerned about (potentially) are those at the top of the list as this represents the majority of where SQL Server is spending it’s time waiting.

This code based on a query written by MVP Glenn Berry and modified by Paul S. Randal so credit goes to them.          
                                                                                                            ----------------------------------------------------------------

WITH [Waits] AS
    (SELECT
        [wait_type],
        [wait_time_ms] / 1000.0 AS [WaitS],
        ([wait_time_ms] - [signal_wait_time_ms]) / 1000.0 AS [ResourceS],
        [signal_wait_time_ms] / 1000.0 AS [SignalS],
        [waiting_tasks_count] AS [WaitCount],
        100.0 * [wait_time_ms] / SUM ([wait_time_ms]) OVER() AS [Percentage],
        ROW_NUMBER() OVER(ORDER BY [wait_time_ms] DESC) AS [RowNum]
    FROM sys.dm_os_wait_stats
    WHERE [wait_type] NOT IN (
        N'CLR_SEMAPHORE',    N'LAZYWRITER_SLEEP',
        N'RESOURCE_QUEUE',   N'SQLTRACE_BUFFER_FLUSH',
        N'SLEEP_TASK',       N'SLEEP_SYSTEMTASK',
        N'WAITFOR',          N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',
        N'CHECKPOINT_QUEUE', N'REQUEST_FOR_DEADLOCK_SEARCH',
        N'XE_TIMER_EVENT',   N'XE_DISPATCHER_JOIN',
        N'LOGMGR_QUEUE',     N'FT_IFTS_SCHEDULER_IDLE_WAIT',
        N'BROKER_TASK_STOP', N'CLR_MANUAL_EVENT',
        N'CLR_AUTO_EVENT',   N'DISPATCHER_QUEUE_SEMAPHORE',
        N'TRACEWRITE',       N'XE_DISPATCHER_WAIT',
        N'BROKER_TO_FLUSH',  N'BROKER_EVENTHANDLER',
        N'FT_IFTSHC_MUTEX',  N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP',
        N'DIRTY_PAGE_POLL',  N'SP_SERVER_DIAGNOSTICS_SLEEP')
    )
SELECT
    [W1].[wait_type] AS [WaitType],
    CAST ([W1].[WaitS] AS DECIMAL(14, 2)) AS [Wait_S],
    CAST ([W1].[ResourceS] AS DECIMAL(14, 2)) AS [Resource_S],
    CAST ([W1].[SignalS] AS DECIMAL(14, 2)) AS [Signal_S],
    [W1].[WaitCount] AS [WaitCount],
    CAST ([W1].[Percentage] AS DECIMAL(4, 2)) AS [Percentage],
    CAST (([W1].[WaitS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgWait_S],
    CAST (([W1].[ResourceS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgRes_S],
    CAST (([W1].[SignalS] / [W1].[WaitCount]) AS DECIMAL (14, 4)) AS [AvgSig_S]
FROM [Waits] AS [W1]
INNER JOIN [Waits] AS [W2]
    ON [W2].[RowNum] <= [W1].[RowNum]
GROUP BY [W1].[RowNum], [W1].[wait_type], [W1].[WaitS],
    [W1].[ResourceS], [W1].[SignalS], [W1].[WaitCount], [W1].[Percentage]
HAVING SUM ([W2].[Percentage]) - [W1].[Percentage] < 95; -- percentage threshold
GO

Output: Will be something like as mentioned below:



Brgds,

Chhavinath Mishra
Sr. Database Administrator

Microsoft Certified IT Professional (MCITP)

Tuesday 8 October 2013

How to Fix a failed In-Place Upgrade/Install from SQL Server 2008/R2 to SQL Server 2008 R2/2012 -- - MSSQLSERVER.INACTIVE

While working on a project ,I've come across situations where I was trying to upgrade SQL Server 2008 R2 to SQL Server 2012. The upgrade failed with error message below. It doesn't matter what version of SQL you're on, upgrading to etc...this issue can pretty much be resolved using this process

--------------------------------------------------------------------------------

The Instance ID ‘MSSQLSERVER’ is already in use by SQL Server instance ‘MSSQLSERVER.INACTIVE’. To continue, specify a unique Instance ID.

--------------------------------------------------------------------------------

Problem/Sympton: I went to upgrade a perfectly working SQL 2008 R2 standard server (which was using a Default Instance) to SQL 2012. The Setup failed halfway through with a random error connecting to SQL Analysis Services (your failure could be different)...then it indicated all I had to do was fix the problem and re-run my SQL 2012 Upgrade...this wasn't true :-)

Brief Background of upgrade process:

Here we have an orphaned SQL instance named MSSQLServer.Inactive. Let’s understand the upgrade process here. During your upgrade, there are two stages:

Pre-PointOfNoReturn

Post- PointOfNoReturn


Point of No Return is a point at which 2008 R2 will take over the instance name and SQL Server 2008 will be then uninstalled.

The REAL Resolution Steps:

Search your machine for files called Datastore_Discovery.xml (depending on how much you've got or done, you might see many of these...just open the most recent one and you'll be fine

Open Datastore_Discovery.xml in an editor...given the formatting, what worked for me was in Visual Studio 2008/2010 and clicking Edit, Advanced, Format Document (this arranges the XML nicely)

What you're looking for is all places where MSSQLServer.Inactive exists in the document as the Instance ID...below is a sample of how the line starts:
<Instance Urn="Machine[@ID='IWE']/Product[@ID='SQLVNEXT']/Instance[@ID='MSSQLSERVER.INACTIVE']" ID="MSSQLSERVER.INACTIVE" Name="MSSQLSERVER.INACTIVE" ........

Scroll along the lines around the above one and find the following value field: ProductCode="{9FFAE13C-6160-4DD0-A67A-DAC5994F81BD}"

There might be multiple ProductCodes, depending on how many times the <Instance URN...> line lists MSSQLServer.Inactive, so make sure to find all ProductCodes...BUT BE CAREFUL that you ignore any VALID instances of SQL. Only look for the ones under MSSQLServer.Inactive entries.

Now open a command line

For each of the ProductCodes that you found for the Inactive SQL Instances, type the following:
msiexec /x {9FFAE13C-6160-4DD0-A67A-DAC5994F81BD}

Do this for each Product Code that relates to an Inactive Instance

Once complete, go back to your SQL installation media and run Setup

Once the main splash screen launches, click on Tools, then Installed SQL Server features discovery report

This will launch a web page listing the SQL Instances and all features per instance

If you still see any MSSQLSERVER.INACTIVE there, you missed one of the ProductCodes and you need to double check. Otherwise, all of the orphaned SQL Instances should now be gone, and you can either Add Features or do a clean Default Instance reinstall

Note : /x means uninstall

I hope this will help you for sure!


Brgds,

Chhavinath Mishra
Sr. Database Administrator

Microsoft Certified IT Professional (MCITP)

Thursday 3 October 2013

xp_readerrorlog V/S sp_readerrorlog parameters in SQL Server



Difference between xp_readerrorlog & sp_readerrorlog

sp_readerrorlog is a stored procedure in the master database that checks that the user is part of the securityadmin group, then calls xp_readerrorlog, passing parameters if available.  Any differences between the two procedures does not affect the output, which means the information returned is the same.

The parameters syntax has been changed in SQL Server 2012 but not documented yet.
sp_readerrorlog 0,1,’node’
xp_readerrorlog 0,1, ‘node’ -- Not supported
sp_readerrorlog 0,1, "node"
xp_readerrorlog 0,1,"node"
Parameters defined
* First Parameter (type int) :- is the number of the log file you want to read, default is "0" for current log.
* Second Parameter (type int), value of 1 reads SQL error logs, value of 2 reads SQL Server Agent logs, with a default value of 1
* Third Parameter varchar (255), is a search string for the log entry, with a default value of NULL
* Forth Parameter varchar (255), is another search string for the log entry, with a default value of NULL

expanding the number of SQL Server error logs

To limit the size of the SQL Server error log, the sp_cycle_errorlog system stored procedure can be issued to start a new error log.

Finally, to address not loosing the historical SQL Server error log, the number of logs should be expanded beyond the default of 7.  The maximum number of logs is 99 for the SQL Server error log.  When it comes to expanding the number of SQL Server error logs, follow these steps:
  • Open Management Studio
  • Navigate to root | Management folder | SQL Server Logs folder
  • Right click on the SQL Server Logs folder and select the 'Configure' option
  • Select the 'Limit the number of error log files before they are recycled' check box
    • Reference the screen shot below as a point of reference
  • Enter the desired number of error logs in the 'Maximum number of error log files'
    • Reference the screen shot below as a point of reference   
  • Press the 'OK' button to save the configuration

Hope you find this interesting.

Brgds,

Chhavinath Mishra
Sr. Database Administrator
Microsoft Certified IT Professional (MCITP)

Friday 27 September 2013

Indirect Checkpoints Feature in SQL Server 2012

I found one interesting feature named Indirect Checkpoints in SQL Server 2012 even there are many more so thought to share with you all.  Using this feature a Database Administrator can manually change the target recovery time (seconds) parameter for a particular user database from its default value of ZERO.

Changing the value of Target Recovery Time parameter higher than ZERO changes the CHECKPOINT behavior of that particular database from Automatic Checkpoint to Indirect Checkpoint. When the Recovery Interval (MIN) value is set to ZERO which is the default value then SQL Server Instance will rely on Automatic Checkpoints and when Recovery Interval (MIN) value is higher than ZERO SQL Server Database Engine relies on Indirect Checkpoint for that particular database. Automatic Checkpoints occur for the database approximately once a minute for all the active databases and the recovery time for the database will be typical less than a minute.

Basic of Checkpoint command in SQL Server?

Just to recap what checkpoint command does in SQL Server. SQL Server Database Engine automatically executes CHECKPOINT command to write all the dirty pages from the Buffer Cache of the current database to the disk. Dirty pages are nothing but the data pages which were stored in the Buffer Cache and were modified means data is not same in disk and buffer, however they are not yet written back to the disk. This process helps SQL Server Database Engine to save time during database recovery process in the event of a sudden system crash or an unexpected SQL Server shutdown.

In the previous versions of SQL Server a Database Administrator can go ahead and change the recovery interval (min) value at the instance level from its default value of ZERO using SP_CONFIGURE System Stored Procedure or using SQL Server Management Studio. However, there was no possibility to change the recovery interval for a particular database.

How to configure Indirect Checkpoints on a database :

USE [master]
GO

ALTER DATABASE [SQL2012DemoDB] SET TARGET_RECOVERY_TIME = 10 SECONDS WITH NO_WAIT

GO

Hope you had good learning.


Brgds,

Chhavinath Mishra
Sr. Database Administrator
Microsoft Certified IT Professional (MCITP)