Search This Blog

Wednesday, April 21, 2010

SQL Queries to get Physical Node Names and Shared Drive from Cluster

Query to get the physical nodes of SQL cluster
SELECT * FROM Fn_VirtualServerNodes()

Query to get the shared drives for a clustered instance
SELECT * FROM fn_servershareddrives()

SQL Query to find if SQL Server is clustered

Query to find Server is clustered
USE MASTER
GO

SELECT @@servername 'ServerName',
ServerType = CASE ServerProperty('IsClustered')
WHEN 1 THEN 'Cluster'
WHEN 0 THEN 'Standalone'
ELSE 'Unknown' END,
@@version 'Version',
LEFT(CAST(SERVERPROPERTY('ProductLevel') as varchar(10)), 3) AS Level,
getdate() 'Date'

Not a valid win32 Application - SQL 2008

Not a valid win32 image - SQL 2008 Install Error Message

Many a times we get wierd errors on installing on specific servers, but we would need
to locate whether its issue with machine we are installing or issue with the setup files
we have copied.

One such case with setup files is reported below where the error message is weird on popup message box and some more info we get on error logs to troubleshoot and ultimately
we find it is a issue with some other DLL whcih needs to be present for setup to continue.

If you encounter the ‘not a valid win32 image’ during SQL 2008 Install or Upgrade it is due to a corrupt DLL and the same would be reported as bad in the detail_global_rules.txt

For which use the Windows resource kit tool called depends.exe(Can be downloaded as free from Microsoft website) to locate the corruption issue.

Let us take for example Microsoft.SqlServer.Configuration.SqlServer_ConfigExtension.dll is the corrupt DLL reported then use the microsoft dependency walker tool to test it
by locating the install directory where the setup files are present, for instance
D:\SQL2008\x86 is install folder then command to use would be:

From the command prompt
D:\sql2008\x86>depends Microsoft.SqlServer.Configuration.SqlServer_ConfigExtension.dll

In the window panel you get the DLL which shows as fault needless to say that warnings can be ignored.

And if you double click the dll which gives error you get the full path of the DLL which reports error and the same can be copied fresh from a SQL 2008 Install CD and we are good to go with SQL 2008 Install.

How to Avoid Cursors - Way to Avoid Cursors - SQL Server

How to Avoid Cursors - Way to Avoid Cursors

Many of us know already that cursor causes performance issues as the data traversed from cursor is stored in tempdb which means lots of Disk I/O is performed and would cause degraded performance.Now let us see how to eliminate cursors from my code.

First we create a sample table called as Employee

/* Creation of Employee Table Data */
CREATE TABLE Employee( Emp_ID INT IDENTITY(1,1),Emp_Name VARCHAR(100),Emp_City VARCHAR(50))

Secondly we insert sample data to the employee table

/* Insert Sample Data into Employee Table Data */
INSERT INTO Employee (Emp_Name,Emp_City)SELECT 'Emp1','MAS'
INSERT INTO Employee (Emp_Name,Emp_City)SELECT 'Emp2','HYD'
INSERT INTO Employee (Emp_Name,Emp_City)SELECT 'Emp3',NULL
INSERT INTO Employee (Emp_Name,Emp_City)SELECT 'Emp4','HYD'
INSERT INTO Employee (Emp_Name,Emp_City)SELECT 'Emp5','SBC'

To get employee data one by one in cursor we use the below code

/*Cursors Usage */
SET NOCOUNT ON

DECLARE @EMP_ID VARCHAR(50)
DECLARE @EMP_NAME VARCHAR(50)

DECLARE EMP_CUR CURSOR FOR
SELECT EMP_ID, EMP_NAME FROM Employee

OPEN EMP_CUR

FETCH NEXT FROM EMP_CUR INTO @EMP_ID ,@EMP_NAME

WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @EMP_ID,@EMP_NAME

FETCH NEXT FROM EMP_CUR INTO @EMP_ID ,@EMP_NAME
END

CLOSE EMP_CUR
DEALLOCATE EMP_CUR

SET NOCOUNT OFF

Now lets see the way to avoid cursors using a simple while loop
/* Code to avoid cursor */
DECLARE @MinSlNo INT
DECLARE @MaxSlNo INT

DECLARE @TBL_EMP TABLE (SNo INT IDENTITY(1,1),
EMP_ID VARCHAR(50),
EMP_NAME VARCHAR(50))

INSERT INTO @TBL_EMP (EMP_ID,EMP_NAME)
SELECT EMP_ID,EMP_NAMEFROM Employee

SELECT @MinSlNo = 1
SELECT @MaxSlNo = MAX(SNo) FROM @TBL_EMP

WHILE @MinSlNo < = @MaxSlNo
BEGIN
SELECT EMP_ID,EMP_NAME
FROM @TBL_EMP
WHERE SNo = @MinSlNo

SELECT @MinSlNo = @MinSlNo + 1
END

Rebuild Log in SQL 2005 - DBCC REBUILD_LOG SQL Server detected a logical consistency-based I/O error

How do I rebuild log in SQL 2005

Error: 824, Severity: 24, State: 2
SQL Server detected a logical consistency-based I/O error: incorrect checksum (expected: 0xb28f8c1a; actual: 0xb37b1a45). It occurred during a read of page (2:0) in database ID 5 at offset 0000000000000000 in file 'D:\Log\TestRebuildLog.ldf'


Rebuild log should be the last option to use(not as first option) in case of log corruption provided we have tried all other recovery or corruption fix options before using this option. But however the same doesnt work in SQL 2005 or higher.

DBCC REBUILD_LOG gives a error message as

Msg 2526, Level 16, State 3, Line 1Incorrect DBCC statement.
Check the documentation for the correct DBCC syntax and options.

So the command to use would be as follows:
Command:
ALTER DATABASE TestRebuildLog REBUILD LOG ON (NAME=TestRebuildLog_Log,FILENAME='D:\Data\TestRebuildLog_Log.ldf')

Monday, April 12, 2010

Run Profiler Trace from TSQL Command

Below mentioned configures trace on TestDB for statements which has filter on 2 tables - T_Table1 & P_Table2, if these filters are removed then it configures all the events happening on SQL Server


-- Create a Queue

declare @rc int
declare @TraceID int
declare @maxfilesize bigint
select @maxfilesize = 5

-- Please replace the text InsertFileNameHere, with an appropriate
-- filename prefixed by a path, e.g., c:\MyFolder\MyTrace. The .trc extension
-- will be appended to the filename automatically. If you are writing from
-- remote server to local drive, please use UNC path and make sure server has
-- write access to your network share

exec @rc = sp_trace_create @TraceID output, 0, N'InsertFileNameHere',
@maxfilesize, NULL

if (@rc != 0)
goto error

-- Client side File and Table cannot be scripted
-- Set the events

declare @on bit
select @on = 1

exec sp_trace_setevent @TraceID, 78, 7, @on
exec sp_trace_setevent @TraceID, 78, 8, @on
exec sp_trace_setevent @TraceID, 78, 9, @on
exec sp_trace_setevent @TraceID, 78, 6, @on
exec sp_trace_setevent @TraceID, 78, 10, @on
exec sp_trace_setevent @TraceID, 78, 14, @on
exec sp_trace_setevent @TraceID, 78, 26, @on
exec sp_trace_setevent @TraceID, 78, 3, @on
exec sp_trace_setevent @TraceID, 78, 11, @on
exec sp_trace_setevent @TraceID, 78, 35, @on
exec sp_trace_setevent @TraceID, 78, 51, @on
exec sp_trace_setevent @TraceID, 78, 12, @on
exec sp_trace_setevent @TraceID, 78, 60, @on
exec sp_trace_setevent @TraceID, 74, 7, @on
exec sp_trace_setevent @TraceID, 74, 8, @on
exec sp_trace_setevent @TraceID, 74, 9, @on
exec sp_trace_setevent @TraceID, 74, 6, @on
exec sp_trace_setevent @TraceID, 74, 10, @on
exec sp_trace_setevent @TraceID, 74, 14, @on
exec sp_trace_setevent @TraceID, 74, 26, @on
exec sp_trace_setevent @TraceID, 74, 3, @on
exec sp_trace_setevent @TraceID, 74, 11, @on
exec sp_trace_setevent @TraceID, 74, 35, @on
exec sp_trace_setevent @TraceID, 74, 51, @on
exec sp_trace_setevent @TraceID, 74, 12, @on
exec sp_trace_setevent @TraceID, 74, 60, @on
exec sp_trace_setevent @TraceID, 53, 7, @on
exec sp_trace_setevent @TraceID, 53, 8, @on
exec sp_trace_setevent @TraceID, 53, 9, @on
exec sp_trace_setevent @TraceID, 53, 6, @on
exec sp_trace_setevent @TraceID, 53, 10, @on
exec sp_trace_setevent @TraceID, 53, 14, @on
exec sp_trace_setevent @TraceID, 53, 26, @on
exec sp_trace_setevent @TraceID, 53, 3, @on
exec sp_trace_setevent @TraceID, 53, 11, @on
exec sp_trace_setevent @TraceID, 53, 35, @on
exec sp_trace_setevent @TraceID, 53, 51, @on
exec sp_trace_setevent @TraceID, 53, 12, @on
exec sp_trace_setevent @TraceID, 53, 60, @on
exec sp_trace_setevent @TraceID, 70, 7, @on
exec sp_trace_setevent @TraceID, 70, 8, @on
exec sp_trace_setevent @TraceID, 70, 9, @on
exec sp_trace_setevent @TraceID, 70, 6, @on
exec sp_trace_setevent @TraceID, 70, 10, @on
exec sp_trace_setevent @TraceID, 70, 14, @on
exec sp_trace_setevent @TraceID, 70, 26, @on
exec sp_trace_setevent @TraceID, 70, 3, @on
exec sp_trace_setevent @TraceID, 70, 11, @on
exec sp_trace_setevent @TraceID, 70, 35, @on
exec sp_trace_setevent @TraceID, 70, 51, @on
exec sp_trace_setevent @TraceID, 70, 12, @on
exec sp_trace_setevent @TraceID, 70, 60, @on
exec sp_trace_setevent @TraceID, 77, 7, @on
exec sp_trace_setevent @TraceID, 77, 8, @on
exec sp_trace_setevent @TraceID, 77, 9, @on
exec sp_trace_setevent @TraceID, 77, 6, @on
exec sp_trace_setevent @TraceID, 77, 10, @on
exec sp_trace_setevent @TraceID, 77, 14, @on
exec sp_trace_setevent @TraceID, 77, 26, @on
exec sp_trace_setevent @TraceID, 77, 3, @on
exec sp_trace_setevent @TraceID, 77, 11, @on
exec sp_trace_setevent @TraceID, 77, 35, @on
exec sp_trace_setevent @TraceID, 77, 51, @on
exec sp_trace_setevent @TraceID, 77, 12, @on
exec sp_trace_setevent @TraceID, 77, 60, @on
exec sp_trace_setevent @TraceID, 14, 7, @on
exec sp_trace_setevent @TraceID, 14, 8, @on
exec sp_trace_setevent @TraceID, 14, 1, @on
exec sp_trace_setevent @TraceID, 14, 9, @on
exec sp_trace_setevent @TraceID, 14, 2, @on
exec sp_trace_setevent @TraceID, 14, 6, @on
exec sp_trace_setevent @TraceID, 14, 10, @on
exec sp_trace_setevent @TraceID, 14, 14, @on
exec sp_trace_setevent @TraceID, 14, 26, @on
exec sp_trace_setevent @TraceID, 14, 3, @on
exec sp_trace_setevent @TraceID, 14, 11, @on
exec sp_trace_setevent @TraceID, 14, 35, @on
exec sp_trace_setevent @TraceID, 14, 51, @on
exec sp_trace_setevent @TraceID, 14, 12, @on
exec sp_trace_setevent @TraceID, 14, 60, @on
exec sp_trace_setevent @TraceID, 17, 7, @on
exec sp_trace_setevent @TraceID, 17, 8, @on
exec sp_trace_setevent @TraceID, 17, 1, @on
exec sp_trace_setevent @TraceID, 17, 9, @on
exec sp_trace_setevent @TraceID, 17, 2, @on
exec sp_trace_setevent @TraceID, 17, 6, @on
exec sp_trace_setevent @TraceID, 17, 10, @on
exec sp_trace_setevent @TraceID, 17, 14, @on
exec sp_trace_setevent @TraceID, 17, 26, @on
exec sp_trace_setevent @TraceID, 17, 3, @on
exec sp_trace_setevent @TraceID, 17, 11, @on
exec sp_trace_setevent @TraceID, 17, 35, @on
exec sp_trace_setevent @TraceID, 17, 51, @on
exec sp_trace_setevent @TraceID, 17, 12, @on
exec sp_trace_setevent @TraceID, 17, 60, @on
exec sp_trace_setevent @TraceID, 100, 7, @on
exec sp_trace_setevent @TraceID, 100, 8, @on
exec sp_trace_setevent @TraceID, 100, 1, @on
exec sp_trace_setevent @TraceID, 100, 9, @on
exec sp_trace_setevent @TraceID, 100, 6, @on
exec sp_trace_setevent @TraceID, 100, 10,@on
exec sp_trace_setevent @TraceID, 100, 14, @on
exec sp_trace_setevent @TraceID, 100, 26, @on
exec sp_trace_setevent @TraceID, 100, 3, @on
exec sp_trace_setevent @TraceID, 100, 11, @on
exec sp_trace_setevent @TraceID, 100, 35, @on
exec sp_trace_setevent @TraceID, 100, 51, @on
exec sp_trace_setevent @TraceID, 100, 12, @on
exec sp_trace_setevent @TraceID, 100, 60, @on
exec sp_trace_setevent @TraceID, 10, 7, @on
exec sp_trace_setevent @TraceID, 10, 15, @on
exec sp_trace_setevent @TraceID, 10, 31, @on
exec sp_trace_setevent @TraceID, 10, 8, @on
exec sp_trace_setevent @TraceID, 10, 1, @on
exec sp_trace_setevent @TraceID, 10, 9, @on
exec sp_trace_setevent @TraceID, 10, 2, @on
exec sp_trace_setevent @TraceID, 10, 10, @on
exec sp_trace_setevent @TraceID, 10, 26, @on
exec sp_trace_setevent @TraceID, 10, 3, @on
exec sp_trace_setevent @TraceID, 10, 11, @on
exec sp_trace_setevent @TraceID, 10, 35, @on
exec sp_trace_setevent @TraceID, 10, 51, @on
exec sp_trace_setevent @TraceID, 10, 12, @on
exec sp_trace_setevent @TraceID, 10, 60, @on
exec sp_trace_setevent @TraceID, 10, 6, @on
exec sp_trace_setevent @TraceID, 10, 14, @on
exec sp_trace_setevent @TraceID, 11, 7, @on
exec sp_trace_setevent @TraceID, 11, 8, @on
exec sp_trace_setevent @TraceID, 11, 1, @on
exec sp_trace_setevent @TraceID, 11, 9, @on
exec sp_trace_setevent @TraceID, 11, 2, @on
exec sp_trace_setevent @TraceID, 11, 6, @on
exec sp_trace_setevent @TraceID, 11, 10, @on
exec sp_trace_setevent @TraceID, 11, 14, @on
exec sp_trace_setevent @TraceID, 11, 26, @on
exec sp_trace_setevent @TraceID, 11, 3, @on
exec sp_trace_setevent @TraceID, 11, 11, @on
exec sp_trace_setevent @TraceID, 11, 35, @on
exec sp_trace_setevent @TraceID, 11, 51, @on
exec sp_trace_setevent @TraceID, 11, 12, @on
exec sp_trace_setevent @TraceID, 11, 60, @on
exec sp_trace_setevent @TraceID, 72, 7, @on
exec sp_trace_setevent @TraceID, 72, 8, @on
exec sp_trace_setevent @TraceID, 72, 9, @on
exec sp_trace_setevent @TraceID, 72, 6, @on
exec sp_trace_setevent @TraceID, 72, 10, @on
exec sp_trace_setevent @TraceID, 72, 14, @on
exec sp_trace_setevent @TraceID, 72, 26, @on
exec sp_trace_setevent @TraceID, 72, 3, @on
exec sp_trace_setevent @TraceID, 72, 11, @on
exec sp_trace_setevent @TraceID, 72, 35, @on
exec sp_trace_setevent @TraceID, 72, 51, @on
exec sp_trace_setevent @TraceID, 72, 12, @on
exec sp_trace_setevent @TraceID, 72, 60, @on
exec sp_trace_setevent @TraceID, 71, 7, @on
exec sp_trace_setevent @TraceID, 71, 8, @on
exec sp_trace_setevent @TraceID, 71, 9, @on
exec sp_trace_setevent @TraceID, 71, 6, @on
exec sp_trace_setevent @TraceID, 71, 10, @on
exec sp_trace_setevent @TraceID, 71, 14, @on
exec sp_trace_setevent @TraceID, 71, 26, @on
exec sp_trace_setevent @TraceID, 71, 3, @on
exec sp_trace_setevent @TraceID, 71, 11, @on
exec sp_trace_setevent @TraceID, 71, 35, @on
exec sp_trace_setevent @TraceID, 71, 51, @on
exec sp_trace_setevent @TraceID, 71, 12, @on
exec sp_trace_setevent @TraceID, 71, 60, @on
exec sp_trace_setevent @TraceID, 12, 7, @on
exec sp_trace_setevent @TraceID, 12, 15, @on
exec sp_trace_setevent @TraceID, 12, 31, @on
exec sp_trace_setevent @TraceID, 12, 8, @on
exec sp_trace_setevent @TraceID, 12, 1, @on
exec sp_trace_setevent @TraceID, 12, 9, @on
exec sp_trace_setevent @TraceID, 12, 6, @on
exec sp_trace_setevent @TraceID, 12, 10, @on
exec sp_trace_setevent @TraceID, 12, 14, @on
exec sp_trace_setevent @TraceID, 12, 26, @on
exec sp_trace_setevent @TraceID, 12, 3, @on
exec sp_trace_setevent @TraceID, 12, 11, @on
exec sp_trace_setevent @TraceID, 12, 35, @on
exec sp_trace_setevent @TraceID, 12, 51, @on
exec sp_trace_setevent @TraceID, 12, 12, @on
exec sp_trace_setevent @TraceID, 12, 60, @on
exec sp_trace_setevent @TraceID, 13, 7, @on
exec sp_trace_setevent @TraceID, 13, 8, @on
exec sp_trace_setevent @TraceID, 13, 1, @on
exec sp_trace_setevent @TraceID, 13, 9, @on
exec sp_trace_setevent @TraceID, 13, 6, @on
exec sp_trace_setevent @TraceID, 13, 10, @on
exec sp_trace_setevent @TraceID, 13, 14, @on
exec sp_trace_setevent @TraceID, 13, 26, @on
exec sp_trace_setevent @TraceID, 13, 3, @on
exec sp_trace_setevent @TraceID, 13, 11, @on
exec sp_trace_setevent @TraceID, 13, 35, @on
exec sp_trace_setevent @TraceID, 13, 51, @on
exec sp_trace_setevent @TraceID, 13, 12, @on
exec sp_trace_setevent @TraceID, 13, 60, @on

-- Set the Filtersdeclare @intfilter intdeclare @bigintfilter bigint

exec sp_trace_setfilter @TraceID, 1, 0, 6, N'%T_Table1%'
exec sp_trace_setfilter @TraceID, 1, 1, 6, N'%P_Table2%'
exec sp_trace_setfilter @TraceID, 10, 0, 7, N'SQL Server Profiler - f4575bc8-bfed-43c3-83c0-a4ef9f643adc'
exec sp_trace_setfilter @TraceID, 35, 0, 6, N'testdb'

-- Set the trace status to startexec sp_trace_setstatus @TraceID, 1
-- display trace id for future references
select TraceID=@TraceID
goto finish

error:
select ErrorCode=@rc

finish:
go


And traceID would be 2 if no other trace is running and below statement
SELECT * FROM sys.fn_trace_getinfo(2)

Will give you info if this trace is running and also where the files are being copied.

SQL Code Reviews

  1. Write comments in your stored procedures, triggers and SQL batches generously, whenever something is not very obvious. This helps other programmers understand your code clearly. Don’t worry about the length of the comments, as it won’t impact the performance, unlike interpreted languages like ASP 2.0.
  2. Do not prefix your stored procedure names with ’sp_’. The prefix sp_ is reserved for system stored procedure that ship with SQL Server. Whenever SQL Server encounters a procedure name starting with sp_,, it first tries to locate the procedure in the master database, then looks for any qualifiers (database, owner) provided, then using dbo as the owner. So, you can really save time in locating the stored procedure by avoiding sp_ prefix. But there is an exception! While creating general purpose stored procedures that are called from all your databases go ahead and prefix those stored procedure names with sp_ and create them in the master database.
  3. Use SET NOCOUNT ON at the beginning of your SQL batches, stored procedures and triggers in production environments, as this suppresses messages like ‘(1 row(s) affected)’ after executing INSERT, UPDATE, DELETE and SELECT statements. This in turn improves the performance of the stored procedures by reducing the network traffic.
    Do not use SELECT * in your queries. Always write the required column names after the SELECT statement, like SELECT CustomerID, CustomerFirstName, City. This technique results in less disk IO and less network traffic and hence better performance.
  4. Do not use the column numbers in the ORDER BY clause as it impairs the readability of the SQL statement. Further, changing the order of columns in the SELECT list has no impact on the ORDER BY when the columns are referred by names instead of numbers. Consider the following example, in which the second query is more readable than the first one:
    SELECT OrderID, OrderDateFROM OrdersORDER BY 2
    SELECT OrderID, OrderDateFROM OrdersORDER BY OrderDate Try to avoid wildcard characters at the beginning of a word while searching using the LIKE keyword, as that results in an index scan, which is defeating the purpose of having an index. The following statement results in an index scan, while the second statement results in an index seek:1. SELECT LocationID FROM Locations WHERE Specialities LIKE ‘%pples’2. SELECT LocationID FROM Locations WHERE Specialities LIKE ‘A%s’ Also avoid searching with not equals operators (<> and NOT) as they result in table and index scans. If you must do heavy text-based searches, consider using the Full-Text search feature of SQL Server for better performance.
  5. Use ‘Derived tables’ wherever possible, as they perform better. Consider the following query to find the second highest salary from Employees table: SELECT MIN(Salary)FROM EmployeesWHERE EmpID IN(SELECT TOP 2 EmpIDFROM EmployeesORDER BY Salary Desc)The same query can be re-written using a derived table as shown below,
    and it performs twice as fast as the above query: SELECT MIN(Salary)FROM(SELECT TOP 2 SalaryFROM EmployeesORDER BY Salary Desc) AS A This is just an example, the results might differ in different scenarios depending upon the database design, indexes, volume of data etc. So, test all the possible ways a query could be written and go with the efficient one. With some practice and understanding of ‘how SQL Server optimizer works’, you will be able to come up with the best possible queries without this trial and error method.
  6. Try to avoid server side cursors as much as possible. Always stick to ’set based approach’ instead of a ‘procedural approach’ for accessing/manipulating data. Cursors can be easily avoided by SELECT statements in many cases. If a cursor is unavoidable, use a simpleWHILE loop instead, to loop through the table. I personally tested and concluded that a WHILE loop is faster than a cursor most of the times. But for a WHILE loop to replace a cursor you need a column (primary key or unique key) to identify each row uniquely and I personally believe every table must have a primary or unique key.
  7. Avoid the creation of temporary tables while processing data, as much as possible, as creating a temporary table means more disk IO. Consider advanced SQL or views or table variables of SQL Server 2000 or derived tables, instead of temporary tables. Keep in mind that, in some cases, using a temporary table performs better than a highly complicated query.
  8. While designing your database, design it keeping ‘performance’ in mind. You can’t really tune performance later, when your database is in production, as it involves rebuilding tables/indexes, re-writing queries. Use the graphical execution plan in Query Analyzer or SHOWPLAN_TEXT or SHOWPLAN_ALL commands to analyze your queries. Make sure your queries do ‘Index seeks’ instead of ‘Index scans’ or ‘Table scans’. A table scan or an index scan is a very bad thing and should be avoided where possible (sometimes when the table is too small or when the whole table needs to be processed, the optimizer will choose a table or index scan).
  9. Use the more readable ANSI-Standard Join clauses instead of the old style joins. With ANSI joins the WHERE clause is used only for filtering data. Where as with older style joins, the WHERE clause handles both the join condition and filtering data. The first of the following two queries shows an old style join, while the second one shows the new ANSI join syntax: SELECT a.au_id, t.titleFROM titles t, authors a, titleauthor taWHEREa.au_id = ta.au_id ANDta.title_id = t.title_id ANDt.title LIKE ‘%Computer%’SELECT a.au_id, t.titleFROM authors aINNER JOINtitleauthor taONa.au_id = ta.au_idINNER JOINtitles t
    ON ta.title_id = t.title_idWHERE t.title LIKE ‘%Computer%’ Be aware that the old style *= and =* left and right outer join syntax may not be supported in a future release of SQL Server, so you are better off adopting the ANSI standard outer join syntax.
  10. Views are generally used to show specific data to specific users based on their interest. Views are also used to restrict access to the base tables by granting permission on only views. Yet another significant use of views is that, they simplify your queries. Incorporate your frequently required complicated joins and calculations into a view, so that you don’t have to repeat those joins/calculations in all your queries, instead just select from the view.
  11. Use ‘User Defined Datatypes’, if a particular column repeats in a lot of your tables, so that the datatype of that column is consistent across all your tables.
    Do not let your front-end applications query/manipulate the data directly using SELECT or INSERT/UPDATE/DELETE statements. Instead, create stored procedures, and let your applications access these stored procedures. This keeps the data access clean and consistent across all the modules of your application, at the same time centralizing the business logic within the database.
  12. Try not to use text, ntext datatypes for storing large textual data. ‘text‘ datatype has some inherent problems associated with it. You can not directly write, update text data using INSERT, UPDATE statements (You have to use special statements like READTEXT, WRITETEXT and UPDATETEXT). There are a lot of bugs associated with replicating tables containing text columns. So, if you don’t have to store more than 8 KB of text, use char(8000) or varchar(8000)datatypes.
    If you have a choice, do not store binary files, image files (Binary large objects or BLOBs) etc. inside the database. Instead store the path to the binary/image file in the database and use that as a pointer to the actual binary file. Retrieving, manipulating these large binary files is better performed outside the database and after all, database is not meant for storing files.
    Use char data type for a column, only when the column is non-nullable. If a char column is nullable, it is treated as a fixed length column in SQL Server 7.0+. So, a char(100), when NULL, will eat up 100 bytes, resulting in space wastage. So, use varchar(100) in this situation. Of course, variable length columns do have a very little processing overhead over fixed length columns. Carefully choose between char and varchar depending up on the length of the data you are going to store.
  13. Avoid dynamic SQL statements as much as possible. Dynamic SQL tends to be slower than static SQL, as SQL Server must generate an execution plan every time at runtime. IF and CASE statements come in handy to avoid dynamic SQL. Another major disadvantage of using dynamic SQL is that, it requires the users to have direct access permissions on all accessed objects like tables and views. Generally, users are given access to the stored procedures which reference the tables, but not directly on the tables. In this case, dynamic SQL will not work. Consider the following scenario, where a user named ‘dSQLuser’ is added to the pubs database, and is granted access to a procedure named ‘dSQLproc’, but not on any other tables in the pubs database. The procedure dSQLproc executes a direct SELECT on titles table and that works. The second statement runs the same SELECT on titles table, using dynamic SQL and it fails with the following error:Server: Msg 229, Level 14, State 5, Line 1SELECT permission denied on object ‘titles’, database ‘pubs’, owner ‘dbo’.To reproduce the above problem, use the following commands:
    sp_addlogin ‘dSQLuser’GOsp_defaultdb ‘dSQLuser’, ‘pubs’USE pubsGOsp_adduser ‘dSQLUser’, ‘dSQLUser’GOCREATE PROC dSQLProcASBEGINSELECT * FROM titles WHERE title_id = ‘BU1032′ –This worksDECLARE @str CHAR(100)SET @str = ‘SELECT * FROM titles WHERE title_id = "BU1032"’EXEC (@str) –This failsENDGOGRANT EXEC ON dSQLProc TO dSQLuserGO Now login to the pubs database using the login dSQLuser and execute the procedure dSQLproc to see the problem.
  14. Consider the following drawbacks before using IDENTITY property for generating primary keys. IDENTITY is very much SQL Server specific, and you will have problems if you want to support different database backends for your application.IDENTITY columns have other inherent problems. IDENTITY columns run out of numbers one day or the other. Numbers can’t be reused automatically, after deleting rows. Replication and IDENTITY columns don’t always get along well. So, come up with an algorithm to generate a primary key, in the front-end or from within the inserting stored procedure. There could be issues with generating your own primary keys too, like concurrency while generating the key, running out of values. So, consider both the options and go with the one that suits you well.
  15. Minimize the usage of NULLs, as they often confuse the front-end applications, unless the applications are coded intelligently to eliminate NULLs or convert the NULLs into some other form. Any expression that deals with NULL results in a NULL output. ISNULL and COALESCE functions are helpful in dealing with NULL values. Here’s an example that explains the problem:Consider the following table, Customers which stores the names of the customers and the middle name can be NULL. CREATE TABLE Customers(FirstName varchar(20),MiddleName varchar(20),LastName varchar(20))Now insert a customer into the table whose name is Tony Blair, without a middle name: INSERT INTO Customers(FirstName, MiddleName, LastName)VALUES (’Tony’,NULL,’Blair’)The following SELECT statement returns NULL, instead of the customer name: SELECT FirstName + ‘ ‘ + MiddleName + ‘ ‘ + LastName FROM CustomersTo avoid this problem, use ISNULL as shown below: SELECT FirstName + ‘ ‘ + ISNULL(MiddleName + ‘ ‘,") + LastName FROM Customers
  16. Use Unicode datatypes like nchar, nvarchar, ntext, if your database is going to store not just plain English characters, but a variety of characters used all over the world. Use these datatypes, only when they are absolutely needed as they need twice as much space as non-unicode datatypes.
  17. Always use a column list in your INSERT statements. This helps in avoiding problems when the table structure changes (like adding a column). Here’s an example which shows the problem.Consider the following table: CREATE TABLE EuropeanCountries(CountryID int PRIMARY KEY,CountryName varchar(25))Here’s an INSERT statement without a column list , that works perfectly: INSERT INTO EuropeanCountriesVALUES (1, ‘Ireland’)Now, let’s add a new column to this table: ALTER TABLE EuropeanCountriesADD EuroSupport bitNow run the above INSERT statement. You get the following error from SQL Server:Server: Msg 213, Level 16, State 4, Line 1Insert Error: Column name or number of supplied values does not match table definition.This problem can be avoided by writing an
    INSERT statement with a column list as shown below: INSERT INTO EuropeanCountries(CountryID, CountryName)VALUES (1, ‘England’)
  18. Perform all your referential integrity checks, data validations using constraints (foreign key and check constraints). These constraints are faster than triggers. So, use triggers only for auditing, custom tasks and validations that can not be performed using these constraints. These constraints save you time as well, as you don’t have to write code for these validations and the RDBMS will do all the work for you.
  19. Always access tables in the same order in all your stored procedures/triggers consistently. This helps in avoiding deadlocks. Other things to keep in mind to avoid deadlocks are: Keep your transactions as short as possible. Touch as less data as possible during a transaction. Never, ever wait for user input in the middle of a transaction. Do not use higher level locking hints or restrictive isolation levels unless they are absolutely needed. Make your front-end applications deadlock-intelligent, that is, these applications should be able to resubmit the transaction incase the previous transaction fails with error 1205. In your applications, process all the results returned by SQL Server immediately, so that the locks on the processed rows are released, hence no blocking.
  20. Offload tasks like string manipulations, concatenations, row numbering, case conversions, type conversions etc. to the front-end applications, if these operations are going to consume more CPU cycles on the database server (It’s okay to do simple string manipulations on the database end though). Also try to do basic validations in the front-end itself during data entry. This saves unnecessary network roundtrips.
  21. If back-end portability is your concern, stay away from bit manipulations with T-SQL, as this is very much RDBMS specific. Further, using bitmaps to represent different states of a particular entity conflicts with the normalization rules.
  22. Consider adding a @Debug parameter to your stored procedures. This can be of bit data type. When a 1 is passed for this parameter, print all the intermediate results, variable contents using SELECT or PRINT statements and when 0 is passed do not print debug information. This helps in quick debugging of stored procedures, as you don’t have to add and remove these PRINT/SELECT statements before and after troubleshooting problems.
  23. Do not call functions repeatedly within your stored procedures, triggers, functions and batches. For example, you might need the length of a string variable in many places of your procedure, but don’t call the LEN function whenever it’s needed, instead, call the LEN function once, and store the result in a variable, for later use.
  24. Make sure your stored procedures always return a value indicating the status. Standardize on the return values of stored procedures for success and failures. The RETURN statement is meant for returning the execution status only, but not data. If you need to return data, use OUTPUT parameters.
  25. If your stored procedure always returns a single row resultset, consider returning the resultset using OUTPUT parameters instead of a SELECT statement, as ADO handles output parameters faster than resultsets returned by SELECT statements.
    Always check the global variable @@ERROR immediately after executing a data manipulation statement (like INSERT/UPDATE/DELETE), so that you can rollback the transaction in case of an error (@@ERROR will be greater than 0 in case of an error). This is important, because, by default, SQL Server will not rollback all the previous changes within a transaction if a particular statement fails. This behavior can be changed by executing SET XACT_ABORT ON. The @@ROWCOUNT variable also plays an important role in determining how many rows were affected by a previous data manipulation (also, retrieval) statement, and based on that you could choose to commit or rollback a particular transaction.
  26. To make SQL Statements more readable, start each clause on a new line and indent when needed. Following is an example: SELECT title_id, titleFROM titlesWHERE title LIKE ‘Computing%’ ANDtitle LIKE ‘Gardening%’
    Though we survived the Y2K, always store 4 digit years in dates (especially, when using char or int datatype columns), instead of 2 digit years to avoid any confusion and problems. This is not a problem with datetime columns, as the century is stored even if you specify a 2 digit year. But it’s always a good practice to specify 4 digit years even with datetime datatype columns.
  27. In your queries and other SQL statements, always represent date in yyyy/mm/dd format. This format will always be interpreted correctly, no matter what the default date format on the SQL Server is. This also prevents the following error, while working with dates: Server: Msg 242, Level 16, State 3, Line 2The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value.
  28. As is true with any other programming language, do not use GOTO or use it sparingly. Excessive usage of GOTO can lead to hard-to-read-and-understand code.
    Do not forget to enforce unique constraints on your alternate keys.
  29. Always be consistent with the usage of case in your code. On a case insensitive server, your code might work fine, but it will fail on a case sensitive SQL Server if your code is not consistent in case. For example, if you create a table in SQL Server or database that has a case-sensitive or binary sort order, all references to the table must use the same case that was specified in the CREATE TABLE statement. If you name the table as ‘MyTable’ in the CREATE TABLE statement and use ‘mytable’ in the SELECT statement, you get an ‘object not found’ or ‘invalid object name’ error.
  30. Though T-SQL has no concept of constants (like the ones in C language), variables will serve the same purpose. Using variables instead of constant values within your SQL statements, improves readability and maintainability of your code. Consider the following example: UPDATE dbo.OrdersSET OrderStatus = 5WHERE OrdDate < ‘2001/10/25′ The same update statement can be re-written in a more readable form as shown below: DECLARE @ORDER_PENDING int SET @ORDER_PENDING = 5 UPDATE dbo.OrdersSET OrderStatus = @ORDER_PENDINGWHERE OrdDate < ‘2001/10/25′
  31. Do not depend on undocumented functionality. The reasons being:- You will not get support from Microsoft, when something goes wrong with your undocumented code- Undocumented functionality is not guaranteed to exist (or behave the same) in a future release or service pack, there by breaking your code
  32. Try not to use system tables directly. System table structures may change in a future release. Wherever possible, use the sp_help* stored procedures or INFORMATION_SCHEMA views. There will be situattions where you cannot avoid accessing system table though!