Archive

Archive for the ‘SQL Server’ Category

SQL SERVER – Rules for Optimizining Any Query – Best Practices for Query Optimization

October 29th, 2009 admin No comments

Best Practices for Query Optimization

  • Table should have primary key
  • Table should have minimum of one clustered index
  • Table should have appropriate amount of non-clustered index
  • Non-clustered index should be created on columns of table based on query which is running
  • Following priority order should be followed when any index is created a) WHERE clause, b) JOIN clause, c) ORDER BY  clause,  d)  SELECT clause
  • Do not to use Views or replace views with original source table
  • Triggers should not be used if possible, incorporate the logic of trigger in stored procedure
  • Remove any adhoc queries and use Stored Procedure instead
  • Check if there is atleast 30% HHD is empty – it improves the performance a bit
  • If possible move the logic of UDF to SP as well
  • Remove * from SELECT and use columns which are only necessary in code
  • Remove any unnecessary joins from table
  • If there is cursor used in query, see if there is any other way to avoid the usage of this (either by SELECT … INTO or INSERT … INTO,     etc)

Source : SqlAuthority

Bulk Insert – SQL Server

August 12th, 2009 admin 6 comments


Sample:
CREATE  PROCEDURE InsertEmployees
/* ———————————————————-
Parameters
In :
@strXML = contains employee list as XML
Example:   ‘<root>
<emp EmpName=”Srinath” EmpSalary=”10000″ />
<emp EmpName=”sree” EmpSalary=”15000″ />
</root>’
———————————————————- */
@strXML varchar(8000)
AS

Declare @intPointer int

exec sp_xml_preparedocument @intPointer output, @strXML

INSERT into employee

SELECT  EmpName, EmpSalary

FROM OpenXml(@intPointer,’/root/emp’,2)

WITH EmpName varchar(20) ‘@EmpName’ , EmpSalary varchar(20) ‘@EmpSalary’)

exec sp_xml_removedocument @intPointer

———————–

EXEC InsertEmployees ‘<root><emp EmpName=”Srinath” EmpSalary=”10000″ /><emp EmpName=”sree” EmpSalary=”15000″ /></root>’

sp_xml_preparedocument

Reads the XML text provided as input, parses the text by using the MSXML parser (Msxmlsql.dll), and provides the parsed document in a state ready for consumption. This parsed document is a tree representation of the various nodes in the XML document: elements, attributes, text, comments, and so on.

sp_xml_preparedocument returns a handle that can be used to access the newly created internal representation of the XML document. This handle is valid for the duration of the session or until the handle is invalidated by executing sp_xml_removedocument.

OPENXML

OPENXML provides a rowset view over an XML document. Because OPENXML is a rowset provider, OPENXML can be used in Transact-SQL statements in which rowset providers such as a table, view, or the OPENROWSET function can appear.

Sample:

OpenXml(@intPointer,’/root/emp’,2)

WITH EmpName varchar(20) ‘@EmpName’ , EmpSalary varchar(20) ‘@EmpSalary’)

sp_xml_removedocument

Removes the internal representation of the XML document specified bythe document handle and invalidates the document handle. To avoidrunning out of memory, will run sp_xml_removedocument to free up thememory.

Some useful sql queries

July 28th, 2009 admin 1 comment

1. Query to delete duplicate values in database table.

Eg: Deletes duplicate Employee names

DELETE FROM Employee WHERE Employeeid IN (
SELECT Employeeid
FROM
(SELECT
Employeename,
Employeeid,
rank() OVER ( PARTITION BY Employeename ORDER BY Employeeid) [ROW_NUMBER]
FROM Employee
)
[Test]
WHERE ROW_NUMBER > 1
)

Query to slect duplicate Employee names:

SELECT Employeeid
FROM
(SELECT
Employeename,
Employeeid,
rank() OVER ( PARTITION BY Employeename ORDER BY Employeeid) [ROW_NUMBER]
FROM Employee
)
[Test]
WHERE ROW_NUMBER > 1

The table must have identity column, which will be used to identify the duplicate records. Table in example is has ID as Identity Column and Columns which have duplicate data are DuplicateColumn1 and DuplicateColumn2.

DELETE
FROM Table_NAME
WHERE ID NOT IN
(
SELECT MAX(ID)
FROM Table_NAME
GROUP BY DuplicateColumn1, DuplicateColumn2)

2. Query to find the Nth largest and smallest element.

nth largest
select min(Salary) from employee where Salary in (select top n Salary from employee order by Salary desc)

nth smallest
select max(Salary) from emp where Salary in (select top n Salary from employee order by Salary asc)

3. Query to display the no. of occurence of an item in a database table.

select EmployeeName,count(EmployeeName)
from Employee
group by EmployeeName

Similarly, we can find the elements with more than one occurence.


select EmployeeName,count(EmployeeName)
from Employee
group by EmployeeName
having count(EmployeeName) > 1

4. How to find Currently Running Queries.

SELECT sqltext.TEXT ‘Current running queries’,
req.session_id [Session Id],
req.status [Status],
req.command [Command],
req.cpu_time [CPU Time],
req.total_elapsed_time [Total Elapsed Time]
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

5. Query to display sequential number of a row of a result set, starting at 1 for the first row.

SELECT EmployeeName, ROW_NUMBER() OVER(ORDER BY EmployeeID DESC) AS ‘Row Number’
FROM Employees

Array Parameter Handling in Stored Procedure

November 14th, 2008 admin No comments

After reading the codeproject article,
I have tried the same using image datatype, but i faced lot of issues

while implementing the same in my project. So i implemented the same
using string, but this will accept
single dimension array only. Here
the trick is to convert the list of values into string separated by
commas
and pass the string into stored procedure, Where we convert the
string into table and then iterate
through the table to get the list
values.

Using the code

This sample explains how to handle arrays in sql server. For this, i have wrote a stored procedure called

Sample_Array_Handling“ and a function “Split”. Stored procedure accepts
a string parameter [array items separated by comma] and prints all
array items.

Steps:
1.Pass the array as string, each array items are separated by ‘,’.
2.Split the string using ‘Split’ function.
3.Create a temporary table and insert the resultset of the step2 into the table.
4.Finally, Use cursor to iterate through the table rows and get each array item.


Sample :
Sample_Array_Handling ‘1,2,3′

Code:


set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

– =============================================
– Author: Srinath
– Create date: May 22 2008
– Description: Array Handling Sample
– =============================================
CREATE PROCEDURE [dbo].[Sample_Array_Handling]
@SampleArray nvarchar(10)
AS

BEGIN

Create table #tempArrayTable (rid varchar(500))
Insert into # tempArrayTable (rid)
(select value from dbo.Split(@SampleArray,’,'))

DECLARE @ArrayItem nvarchar(100)
DECLARE @Array_Cursor CURSOR
SET @Array_Cursor = CURSOR FAST_FORWARD FOR select rid
from # tempArrayTable

OPEN @ Array_Cursor

FETCH NEXT FROM @ Array_Cursor INTO @ArrayItem

WHILE @@FETCH_STATUS = 0
BEGIN

print @ArrayItem

FETCH NEXT FROM @ Array_Cursor INTO @ArrayItem

END

Close Array_Cursor
deallocate Array_Cursor

END

String Split Function :

Code:

– =============================================
– To Split the string and returns a table
– =============================================
CREATE FUNCTION [dbo].[Split](@sText varchar(8000), @sDelim varchar(20) = ‘
‘)
RETURNS @retArray TABLE (idx smallint Primary Key, value varchar(8000))
AS
BEGIN
DECLARE @idx int,
@value varchar(8000),
@bcontinue bit,
@iStrike int,
@iDelimlength int

IF @sDelim = ‘Space’
BEGIN
SET @sDelim = ‘ ‘
END

SET @idx = 0
SET @sText = LTrim(RTrim(@sText))
SET @iDelimlength = DATALENGTH(@sDelim)
SET @bcontinue = 1

if(Len(@sText) = 0)
return

IF NOT ((@iDelimlength = 0) or (@sDelim = ‘Empty’))
BEGIN
WHILE @bcontinue = 1
BEGIN

–If you can find the delimiter in the text, retrieve the first element and
–insert it with its index into the return table.

IF CHARINDEX(@sDelim, @sText)>0
BEGIN
SET @value = SUBSTRING(@sText,1, CHARINDEX(@sDelim,@sText)-1)
BEGIN
INSERT @retArray (idx, value)
VALUES (@idx, @value)
END

–Trim the element and its delimiter from the front of the string.
–Increment the index and loop.
SET @iStrike = DATALENGTH(@value) + @iDelimlength
SET @idx = @idx + 1
SET @sText = LTrim(Right(@sText,DATALENGTH(@sText) – @iStrike))

END
ELSE
BEGIN
–If you can’t find the delimiter in the text, @sText is the last value in
–@retArray.
SET @value = @sText
BEGIN
INSERT @retArray (idx, value)
VALUES (@idx, @value)
END
–Exit the WHILE loop.
SET @bcontinue = 0
END
END
END
ELSE
BEGIN
WHILE @bcontinue=1
BEGIN
–If the delimiter is an empty string, check for remaining text
–instead of a delimiter. Insert the first character into the
–retArray table. Trim the character from the front of the string.
–Increment the index and loop.
IF DATALENGTH(@sText)>1
BEGIN
SET @value = SUBSTRING(@sText,1,1)
BEGIN
INSERT @retArray (idx, value)
VALUES (@idx, @value)
END
SET @idx = @idx+1
SET @sText = SUBSTRING(@sText,2,DATALENGTH(@sText)-1)

END
ELSE
BEGIN
–One character remains.
–Insert the character, and exit the WHILE loop.
INSERT @retArray (idx, value)
VALUES (@idx, @sText)
SET @bcontinue = 0
END
END

END

RETURN
END

You
might have come across situation where you want split strings or create
table from a list of values.
In such situations, you can use the Split
function i have attached with this article.

In this thread, i have used cursor for fetching values from table. You can avoid usage of cursor, for more informations refer this article

For attachments, Please refer this link My code4asp.net forum post or codeproject article

Categories: SQL Server Tags: