Search This Blog

Thursday, January 10, 2013

SQL Server Performance Killers

1)   Poor indexing
2)   Inaccurate statistics
3)   Excessive blocking and deadlocks
4)   Non-set-based operations, usually T-SQL cursors
5)   Poor query design
6)   Poor database design
7)   Excessive fragmentation
8)   Non-reusable execution plans
9)   Poor execution plans, usually caused by parameter sniffing
10)Frequent recompilation of execution plans
11)Improper use of cursors
12)Improper configuration of the database log
13)Excessive use or improper configuration of tempdb
 

Thursday, April 26, 2012

Recovering SQL Server Database From Suspect Mode

Follow below steps to recover database from suspect mode:

  1. ALTER DATABASE [database_name] SET EMERGENCY 
  2. DBCC checkdb('database_name') 
  3. ALTER DATABASE [database_name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE 
  4. DBCC CheckDB ('database_name', REPAIR_ALLOW_DATA_LOSS)
  5. ALTER DATABASE [database_name SET MULTI_USER

If it does not work for you, then go for thrid party tool or restore database from available backups.

Sunday, August 7, 2011

Playing with NULL


A NULL values is an unknown value, different from a zero or an empty value.
There are few points that must be remembered when you are dealing with NULL values:
1.       No two NULL values are equal.
2.       Comparison between two NULL values or between one NULL and any other values results in an UNKNOWN value.
3.       Logical (e.g. AND, OR etc.) and Comparison (e.g. =, >, < etc.) Operators can return a third result UNKNOWN during comparison between two expressions.
4.       Concatenating two string values, if one of strings is Null, then result will be a null value. (SET CONCAT_NULL_YIELDS_NULL is ON)

How to manipulate NULL values?

There are three cases where you can face NULL values occurrences,

First case – Conditional expressions – used in WHERE clause, with IF statements, or with CASE statements, all above are for comparison between columns or between a column and a value.

Second case – Data sets returned through a selection or SELECT statement. Here you apply comparisons and conversion by evaluating or equating the values.

Third case – DML Statements, mostly considered statement here is INSERT statement, for NULL allowable columns, where you are not providing values for them, NULL is inserted.

You can use mix of below given functions and clauses for both first and second cases, while for third case if the columns are null allowable you can specify DEFAULT constraint with some appropriate default value.

There are three functions and two clauses that you can use to deal with NULL values.

Functions:
a.       ISNULL (Check_Expression, Replacement_value) – Replaces NULL with the specified replacement value.
b.      NULLIF (Expression, Expression) – Returns a NULL value if two provided expressions are equal or first expression if they are not equal.
c.       COALESCE (Expression,…..n) – Returns first non-NULL expression among n expressions or NULL if all expressions contain null.
Clauses:
a.       Expression IS NULL – Determines whether the specified expression is null. Returns TRUE if expression contains a null value otherwise FALSE.
b.      Expression IS NOT NULL – same as above, but it negates the result of above clause. FALSE for the expression containing null values otherwise TRUE.
Example:

/*
@String1 has default value.
@String2 has null as default.
@String3 has null as default.
*/

DECLARE @String1 varchar(10) = 'String1'
            ,@String2 varchar(10)
            ,@String3 varchar(10)
           
SELECT ISNULL(@String2, @String1) AS "ISNULL"
SELECT NULLIF(@String2, @String3) AS "NULLIFF"
SELECT COALESCE(@String2, @String3, @String1) AS "COALESCE"

SELECT 1 AS "IS NULL" WHERE @String2 IS NULL
SELECT 1 AS "IS NOT NULL" WHERE @String1 IS NOT NULL


Wednesday, December 15, 2010

Microsoft® SQL Server® code-named 'Denali' - Community Technology Preview 1 (CTP1)

Overview


SQL Server code-named 'Denali' helps empowers organizations to be more agile in today’s competitive market. Customers will more efficiently deliver mission-critical solutions through a highly scalable and available platform. Industry-leading tools help developers quickly build innovative applications while data integration and management tools help deliver credible data reliably to the right users and extended managed self-service BI capabilities enable meaningful insights.

With SQL Server code-named 'Denali' customers will benefit from the following added investments:
  • Enhanced mission-critical platform: A highly available and scalable platform designed to with greater flexibility, lower TCO, ease of use, and the performance required by the most mission-critical applications.
  • Developer and IT Productivity: New additional tools will help developers build innovative applications with reduced time-to-market while IT professionals benefit from greater operational control and ease of use.
  • Pervasive Insight: Stunning new managed self-service experiences for end users and holistic data integration and management tools will help deliver consistent, credible data to the right users at the right time.
Click Title (to reach to download files and further reading...)

Tuesday, December 14, 2010

Monitoring Transactional Replication Status - SQL Server 2005, 2008, 2008 R2

USE DISTRIBUTION
GO
SELECT
      s.agent_id
      ,a.id
      ,s.article_id
      ,a.subscriber_id
      ,ar.Source_owner
      ,ar.Source_object
      ,ar.destination_owner
      ,ar.destination_object
      ,s.undelivcmdsindistdb
      ,a.publisher_db
      ,a.subscriber_db
      ,a.publication
FROM distribution.dbo.msdistribution_status s with (nolock)
INNER JOIN (SELECT * FROM msdistribution_agents with (nolock)) AS a ON a.id = s.agent_id
INNER JOIN (SELECT * FROM msarticles with (nolock)) AS ar
            ON ar.article_id = s.article_id
                  AND a.publisher_Db = ar.publisher_db
WHERE a.subscriber_db<>'virtual'
AND s.undelivcmdsindistdb>0
ORDER BY  s.undelivcmdsindistdb DESC

Monday, November 1, 2010

DDL EVENTS List - SQL Server 2008/R2

Below are the all events with their hierarchy and scope that you can use to implement DDL triggers at both Server or Database Level.
You can create trigger to fire on all events defined under a group, then you can create trigger for that particular group like "DDL_TABLE_EVENTS", this trigger will fire on all three sub-events defined under this group; these are CREATE_TABLE, ALTER_TABLE and DROP_TABLE. Similarly if you want to have a trigger to fire only for a particular event in an event group, then specify only that particular event like "ALTER_TABLE".
See example below as well:




Example 01: Database Level Trigger for a particular event
-- DDL Trigger to prevent column changes on a Database
CREATE TRIGGER ColumnChanges
ON DATABASE
FOR ALTER_TABLE
AS
BEGIN
-- Detect whether a column was created/altered/dropped.
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)')
RAISERROR ('Table schema cannot be modified in this database.', 16, 1);
ROLLBACK;
END
GO


Example 02: Server Level Trigger for a particular event
-- DDL Trigger to prevent column changes for all databases on an instance
CREATE TRIGGER ColumnChanges
ON ALL SERVER
FOR ALTER_TABLE
AS
BEGIN
-- Detect whether a column was created/altered/dropped.
SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]', 'nvarchar(max)')
RAISERROR ('Table schema cannot be modified in this database.', 16, 1);
ROLLBACK;
END
GO


Friday, October 29, 2010

Script: view information of currently running SQL Server Jobs

Below script returns five (5) columns result set as output. You can further enhance this query to accommodate your requirement.

  1. Job_Name: This is job’s registered name on the server’s instance.
  2. Last_Executed_Step_ID: This is the ID of the last executed step in the job. E.g. if a job has 4 steps, and currently it is running 3rd step, so last executed step will be 2 and it will be populated with 2 against Job’s 2nd step row, while all other steps rows will have 0.
  3. Step_ID: This query returns all steps included in the job along with their id, while 2nd column, returns id same as in this column.
  4. Step_Name: This reflects job step name that was given during job creation.
  5. Start_Execution_Date: This column returns execution date and time of this job. So you can get an idea when this started execution.


SELECT 
LTRIM(RTRIM(CONVERT(VARCHAR(100),j.name))) job_name
,ISNULL(a.last_executed_step_id,'') last_executed_step_id
,s.step_id
,RTRIM(CONVERT(VARCHAR(100),s.step_name))step_name
,a.start_execution_Date


FROM msdb.dbo.sysjobs j WITH (NOLOCK)
INNER JOIN msdb.dbo.sysjobsteps s WITH (NOLOCK) ON j.job_id = s.job_id
LEFT OUTER JOIN msdb.dbo.sysjobactivity a WITH (NOLOCK) ON j.job_id=a.job_id
AND (s.step_id=a.last_executed_step_id OR a.last_executed_Step_id IS NULL)
AND run_requested_date>=CAST(CONVERT(VARCHAR,GETDATE(),101) AS DATETIME)
AND stop_execution_Date IS NULL


WHERE j.enabled=1
AND j.category_id IN (0,1,2,3,4,5,98,99)
AND j.job_id in 
(SELECT job_id FROM msdb.dbo.sysjobactivity WITH (NOLOCK)
WHERE start_execution_date>= CAST(CONVERT(VARCHAR,GETDATE(),101) AS DATETIME) 
AND stop_execution_date IS NULL )


ORDER BY 1,3


Monday, October 25, 2010

Compound Operators - SQL SERVER 2008/R2

You are aware about arithmetic, bitwise and assignment operators, don’t worry if you are not, see below you will get an idea about them.

Arithmetic Operators: There are 5 arithmetic operators that are Plus (+), Minus (-), Divide (/), Multiply (*) and Modulo (%)

Bitwise Operators: There are three bitwise operators that are Bitwise AND (&), Bitwise OR (|) and Bitwise Exclusive OR (^).

Assignment Operators: There is only one assignment operator Equal to (=)

Example to use them (in Older version):

-- Arithmetic
DECLARE @var INT
SET @var = 1 -- Assignment

SET @var = @var + 2 -- Increment and them assignment
SELECT @var

SET @var = @var - 1 -- decrement and them assignment
SELECT @var

SET @var = @var & 3 -- Bitwise AND and then assignment
SELECT @var

SET @var = @var | 3 -- Bitwise AND and then assignment
SELECT @var


You can see above old method for increment or decrement and then assignment by using Plus (+) and Minus (-) operators. You can use other operators as well in the same way. But this was an old way for of manipulation and then result assignment. We will see enhancement in operator utilization from SQL Server 2008 that is Compound Operators.


Compound Operators:
These operators defined by combining one operator from Arithmetic/Bitwise and 2nd operator from Assignment. It first performs associated operation on left operand with right operand and then saves result to left operand.

These are 8 in numbers.

  1. += (Add EQUALS), you can use it for string concatenation as well.
  2. -= (Minus EQUALS)
  3. *= (Multiply EQUALS)
  4. /= (Divide EQUALS)
  5. %= (Modulo EQUALS)
  6. &= (Bitwise AND EQUALS)
  7. |= (Bitwise OR EQUALS)
  8. ^= (Bitwise Exclusive OR EQUALS)


Example:
Compare this example with above one:


DECLARE @var INT
SET @var = 1 -- Assignment

SET @var += 2 -- Increment and them assignment
SELECT @var

SET @var -= 1 -- Increment and them assignment
SELECT @var


SET @var &= 3 -- Bitwise AND and then assignment
SELECT @var

SET @var |= 3 -- Bitwise AND and then assignment
SELECT @var

Wednesday, October 20, 2010

Enhanced VALUES Clause (ROW Constructor) – SQL SERVER 2008 / R2

 Old Style:
If you see at previous versions of SQL Server (Older than 2008), you were able to insert only a single row by using values clause.

INSERT INTO dbo.mytable(id, val) VALUES(1, 'First Value');

Or

If you were inserting through SELECT statement, you were able to specify a single row values or by combining multiple rows by using UNION/UION ALL operator.

INSERT INTO dbo.mytable(id, val)
SELECT 1 AS ID, 'First Value' AS VAL
UNION ALL SELECT 2, 'Second Value'
UNION ALL SELECT 3, 'Thrid Value'


New Style:
Now, using SQL Server 2008 or Later, you can find enhanced version of VALUES clause that works as a collection of row(s). You can specify up to 1000 rows by using this clause. Further, it treats it a single transaction, in case of failure, all rows will be rolled back.

Try this example:


CREATE TABLE dbo.mytable
(ID INT,
 VAL VARCHAR(100)
 );

 -- Inertion by using Values clause
 INSERT INTO dbo.mytable (ID, VAL )
 VALUES (1, 'First Value')
 ,(2, 'Second Value')
 ,(3, 'Third Value')


-- Insertion by using Values clause with Select Statement
 INSERT INTO dbo.mytable (ID, VAL )
 SELECT *
 FROM (VALUES (1, 'First Value')
 ,(2, 'Second Value')
 ,(3, 'Third Value') ) as temp(ID, VAL)


Further, you can use VALUES clause to parse a string of multiple parameter values to get them in rows.

Try below script:

DECLARE @StrValues NVARCHAR(100)
DECLARE @Str NVARCHAR(500)
SET @StrValues = '(''A''),(''B''),(''C'')'
SET @Str = 'SELECT * FROM (VALUES ' + @StrValues + ' ) as Temp(Col1)'
EXEC SP_EXECUTESQL @Str

Friday, October 15, 2010

SQL Server 2008 SP2 Release (download link)

What's New:
15K partitioning Improvement.
Introduced support for a maximum of 15,000 partitions in tables and indexes in Microsoft SQL Server 2008 Service Pack 2 in the Enterprise, Developer and Evaluation Editions.

Reporting Services in SharePoint Integrated Mode. SQL Server 2008 SP2 provides updates for Reporting Services integration with SharePoint products. SQL Server 2008 SP2 report servers can integrate with SharePoint 2010 products. SQL Server 2008 SP2 also provides a new add-in to support the integration of SQL Server 2008 R2 report servers with SharePoint 2007 products.

SQL Server 2008 R2 Application and Multi-Server Management Compatibility with SQL Server 2008.

SQL Server 2008 Instance Management.With SP2 applied, an instance of the SQL Server 2008 Database Engine can be enrolled with a SQL Server 2008 R2 Utility Control Point as a managed instance of SQL Server.

Data-tier Application (DAC) Support.Instances of the SQL Server 2008 Database Engine support all DAC operations delivered in SQL Server 2008 R2 after SP2 has been applied. You can deploy, upgrade, register, extract, and delete DACs. SP2 does not upgrade the SQL Server 2008 client tools to support DACs. You must use the SQL Server 2008 R2 client tools, such as SQL Server Management Studio, to perform DAC operations. A data-tier application is an entity that contains all of the database objects and instance objects used by an application. A DAC provides a single unit for authoring, deploying, and managing the data-tier objects.

Monday, October 11, 2010

Moving User Database Files in SQL Server 2000

0. Take Full backup before moving files

1. Set database in single user mode
use master
go

exec sp_dboption testdb2000,'single user','true'
go

2. Get path of database files

Exec sp_helpdb testdb2000
go

3. Save location of all files

C:\Program Files\Microsoft SQL Server\MSSQL$INS2000\data\TestDB2000_Data.MDF
C:\Program Files\Microsoft SQL Server\MSSQL$INS2000\data\TestDB2000_Log.LDF

4. De-attach this database

Exec sp_detach_db @dbname = 'testdb2000','true'
go

5. Copy all files available in step 2 and paste them to a new location
6. Rename them on their old location, just in case of any issue to revert back changes
7. After copying them to a new location, attach these files from new location to this database, you can attach upto 16 files through this procedure.

Exec sp_attach_db @dbname = 'testdb2000', @filename1 = 'd:\testdb2000\TestDB2000_Data.MDF', @filename2 = 'd:\testdb2000\TestDB2000_Log.LDF'
go

8. Connect to user database and verify changes, after verification, remove old file from old location

Saturday, April 25, 2009

Utility to see Logins and users on an instance

Use below link to download it:

http://cid-2512e6af14d229c4.skydrive.live.com/self.aspx/SQL%20Server%20Utilities/Instance%20Users%20and%20Logins%20Details.zip

Description:
You can see available logins on an instance and users list in a databases, their fixed roles at server and database level, categorized as server login and database user, Object level permission details.

Pre-requistes:
.Net Framwork 2.0 installed
Only for SQL Server 2005+

Wednesday, April 15, 2009

List of Running Sessions and their Requests on an Instance

Download this free utility by clicking below link:

http://cid-2512e6af14d229c4.skydrive.live.com/self.aspx/SQL%20Server%20Utilities/Running%20Requests%20on%20an%20Instance.zip

Pre-requists:
.Net Framwork 2.0 or +
Only for SQL Server 2005+
Developed using VB .Net

Description:
This is an executable file that is available in zip formate at above link.
You can view all logins sessions and their running requests on an instance by providing SQL Server instance name or IP Address and can filter them by database by getting all db name or providing db name by writing in combo box.

Wednesday, February 18, 2009

Moving database files

We have three kinds of database files: log files (*.ldf), primary data files (*.mdf) and secondary data files (*.ndf).

Primary data file is the starting point for a database and points to all other files in it. Each database has one primary data file. There can be 0 or >0 secondary data files in a database to make up data files other than primary data file. Log files hold all log information that is used to recover database. There must be at least one log file for a database but it can be more than one.

If you initially create a database by using default locations or defining new one at run time. After sometime if you want to move database files to a new location by considering capacity of current disk or for any other system maintenance.

How you will move them?

Let’s see below!

We have two considerations to move database files from one location to another.
a) Planned relocation procedure
b) Relocation for scheduled disk maintenance

Although you can follow both procedures alternatively, but it depends on the environment and scenario in which you are working. If your concern with only db files move then “Planned relocation procedure” is most suitable in every scenario, because it affects the processes only for relevant database, till the time it comes online.

Planned relocation procedure:
You can follow this procedure when you require less downtime for production, or to minimize relocation impact on other process like replication, log shipping etc, mostly when you want to move files permanently to another location without affecting other databases.

Steps are:
1) Run ALTER DATABASE [database name] SET OFFLINE.
2) Move file to new location
3) Run ALTER DATABASE [database name] MODIFY FILE ( NAME = [logical name], FILENAME = 'path and filename'.
4) Run ALTER DATABASE [database name] SET ONLINE.


Relocation for scheduled disk maintenance:
You can follow this procedure, when you need to move database files to another location to perform any server or disk maintenance activity, like disk de-fragment and you can bear downtime for all databases available on that particular server.


Steps are:
1) Run ALTER DATABASE [database name] MODIFY FILE ( NAME = [logical name], FILENAME = 'path and filename'.
2) Sql server is stopped or system is shutdown to perform maintenance.
3) Move file to new location.
4) Restart server.

Tuesday, February 10, 2009

Preliminary checks for MS DTC

To dig further to evaluate MS DTC error, check below things is in place.

  1. You are able to ping both server from each other. If not then define them in their host files and try to ping them again, till it resolves.
  2. All MS DTC configurations should be same on both servers.
    a) NETWORK DTC Access
    b) Client and Administration (Allow remote clients, Allow remote administration)
    c) Transaction Communication Manager (Allow Inbound, Allow outbound, Mutual authentication required, Incoming caller authentication required, No authentication required, Enable TIP Transactions)
    d) Enable XA Transaction
    e) DTC Logon Account [Should be NT Authoriy/Networkservice]

    Permissions: You must have administrator access to play with above configurations.

    How to access MS DTC?
    Control Panel > Administrative Tools > Component Services > Component Services > Computers > My Computer > right click on it and then click on Properties and then click on MS DTC tab.

    How to access Host file?
    "C:\Windows\System32\Drive\etc\", you will find a file with the name of "Host"

Wednesday, January 14, 2009

Database & Disk space analysis

BEGIN

CREATE TABLE #LOGSPACE
(DBNAME VARCHAR(100)
,LOGSIZE DECIMAL(30,10)
,LOGSPACE DECIMAL(30,10)
,STATUS INT
)

CREATE TABLE #DRIVESPACE
(DRIVE VARCHAR(2)
,DRIVESPACE BIGINT
)

INSERT INTO #LOGSPACE
EXEC ('DBCC SQLPERF(LOGSPACE)')

INSERT
INTO #DRIVESPACE
EXEC ('MASTER.SYS.XP_FIXEDDRIVES')

SELECT F.TYPE_DESC DBFILES
,LEFT(F.PHYSICAL_NAME,1) DRIVE
,F.STATE_DESC DBSTATE
,((F.[SIZE]*8)/1024.00)/1024.00 DBCURRENTSIZE
,ISNULL(((A.RESERVED*8)/1024.00)/1024.00 - ((D.LOGSIZE/1024.00) * (D.LOGSPACE/100.00)),(L.LOGSIZE/1024.00) * (L.LOGSPACE/100.00)) DBRESERVEDSIZE
,CASE WHEN F.IS_PERCENT_GROWTH=0 THEN 'PAGES' WHEN F.IS_PERCENT_GROWTH=1 THEN 'PERCENTAGE' END DBGROWTHTYPE
,F.GROWTH DBGROWTHVALUE
,CASE WHEN F.IS_PERCENT_GROWTH=0 THEN ((F.GROWTH*8)/1024.00)/1024.00 WHEN F.IS_PERCENT_GROWTH=1 THEN (((F.[SIZE]*8)/1024.00)*(F.GROWTH/100.00))/1024.00 END DBGROWTHSIZE
,CASE WHEN F.MAX_SIZE=0 THEN 'FIXED SIZE' WHEN F.MAX_SIZE=-1 THEN 'UNLIMITED' ELSE CONVERT(VARCHAR,((CONVERT(BIGINT,F.MAX_SIZE)*8)/1024.00)/1024.00) END MAX_SIZE
,DS.DRIVESPACE/1024.00 FREESPACEONDRIVE
INTO #SPACEANALYSISREPORT
FROM SYS.DATABASE_FILES F
INNER JOIN #DRIVESPACE DS ON DS.DRIVE = LEFT(F.PHYSICAL_NAME,1)
LEFT OUTER JOIN #LOGSPACE L ON L.DBNAME = DB_NAME() AND F.TYPE_DESC='LOG'
LEFT OUTER JOIN #LOGSPACE D ON D.DBNAME = DB_NAME() AND F.TYPE_DESC='ROWS'
LEFT OUTER JOIN
(SELECT DB_ID() DATABASE_ID, 'ROWS' TYPE_DESC,SUM(TOTAL_PAGES) RESERVED, SUM(USED_PAGES) USED FROM SYS.ALLOCATION_UNITS) A ON A.TYPE_DESC=F.TYPE_DESC

SELECT * FROM #SPACEANALYSISREPORT

DROP TABLE #LOGSPACE
DROP TABLE #DRIVESPACE
DROP TABLE #SPACEANALYSISREPORT

END