Monday, July 21, 2008

Turning Tables into Delimited Text

The world isn’t relational. It’s not divided into rows and columns. Sometimes
when there’s a list associated with a row, it’s better to show the list
as comma-separated text rather than try to preserve a relational presentation.
I use this technique on reports and sometimes on online grids. The
UDFs that implement this technique are not multistatement but scalar.
CREATE FUNCTION udf_Titles_AuthorList (
@title_id char(6) -- title ID from pubs database
) RETURNS varchar(255) -- List of authors
-- No SCHEMABINDING reads data from another DB
/*
* Returns a comma-separated list of the last name of all
* authors for a title.
*
* Example:
Select Title, dbo.udf_Titles_AuthorList(title_id) as [Authors]
FROM pubs..titles ORDER by Title
****************************************************************/
AS BEGIN
DECLARE @lname varchar(40) -- one last name.
, @sList varchar(255) -- working list
SET @sList = ''
DECLARE BookAuthors CURSOR FAST_FORWARD FOR
SELECT au_lname
FROM pubs..Authors A
INNER JOIN pubs..titleAuthor ta
ON A.au_id = ta.au_id
WHERE ta.title_ID = @Title_ID
ORDER BY au_lname
OPEN BookAuthors
FETCH BookAuthors INTO @lname
WHILE @@Fetch_status = 0 BEGIN
SET @sList = CASE WHEN LEN(@sList) > 0
THEN @sList + ', ' + @lname
ELSE @lname
END
FETCH BookAuthors INTO @lname
END
CLOSE BookAuthors
DEALLOCATE BookAuthors
RETURN @sList
END

Thursday, July 17, 2008

CAST and CONVERT (T-SQL)

How to use cast and convert check out this link

Renaming a Stored Procedure


Syntax:
sp_rename 'procedure_name1', 'procedure_name2'
procedure_name1
The current name of the stored procedure
procedure_name2
The new name of the stored procedure.

A stored procedure can be renamed. The new name should follow the rules for identifiers.

Examples

Code:
EXEC sp_rename 'spGetAvgGrade', 'spNewAvgGrade';
Output:
Caution: Changing any part of an object name could break scripts and stored procedures.
The object was renamed to 'spNewAvgGrade'.
Explanation:

In the above example we change the name of the stored procedure spGetAvgGrade to spNewAvgGrade.

Tuesday, July 15, 2008

Implementing Custom Paging in ASP.NET with SQL Server 2005

Why Custom Paging?
Custom paging allows you to get limited number records from a large database table that saves processing time of your database server as well as your application server and makes your application scalable, efficient and fast.


In this article, I am going to explain how to create a stored procedure in SQL Server 2005 that allows you to pass startRowIndex and pageSize as a parameter and return you the number of records starting from that row index to the page size specified. It was possible in the SQL Server 2000 too but it was not as easy as in SQL Server 2005 is.


-- EXEC LoadPagedArticles 10, 5

CREATE PROCEDURE LoadPagedArticles

-- Add the parameters for the stored procedure here

@startRowIndex int,

@pageSize int

AS

BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from

-- interfering with SELECT statements.

SET NOCOUNT ON;

-- increase the startRowIndex by 1 to avoid returning the last record again

SET @startRowIndex = @startRowIndex + 1

BEGIN

SELECT * FROM (

Select *,

ROW_NUMBER() OVER (ORDER BY AutoID ASC) as RowNum

FROM Articles

) as ArticleList

WHERE RowNum BETWEEN @startRowIndex AND (@startRowIndex + @pageSize) - 1

ORDER BY AutoID ASC

END

END

GO

Tuesday, July 8, 2008

Execute Dynamic SQL commands in SQL Server




In some applications having hard coded SQL statements is not appealing,
because of the dynamic nature of the queries being issued against the
database server. Because of this sometimes there is a need to dynamically
create
a SQL statement on the fly and then run that command. This can be
done quite simply from the application perspective where the statement is
built on the fly whether you are using ASP.NET, ColdFusion or any other programming
language
. But how do you do this from within a SQL Server stored procedure?

SQL Server offers a few ways of running a dynamically built SQL statement.
These ways are:
1. Writing a query with parameters
2. Using EXEC
3. Using sp_executesql
Writing a query with parameters
This first approach is pretty straight forward if you only need to pass parameters
into
your WHERE clause of your SQL statement. Let's say we need to find all records
from the customers table where City = '
London'. This can be done easily such as
the following example shows.
DECLARE @city varchar(75)
SET @city = '
London'
SELECT * FROM customers WHERE City = @city
2. Using EXEC
With this approach you are building the SQL statement on the fly and can pretty
much do whatever you need to in order to construct the statement. Let'
s say we
want to be able to pass in the column list along with the city.
For this example we want to get columns CustomerID, ContactName and City where
City = 'London'.
As you can see from this example handling the @city value is not at straight
forward, because you also need to define the extra quotes in order to pass a
character value into the query. These extra quotes could also be done within the
statement
, but either way you need to specify the extra single quotes in order for
the query to be built correctly and therefore run.
DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)
3. sp_exectesql
With this approach you have the ability to still dynamically build the query,
but you are also able to still use parameters as you could in example 1.
This saves the need to have to deal with the extra quotes to get the query to
build correctly. In addition, with using this approach you can ensure that the
data values being passed into the query are the correct datatypes.
DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Tips and Trics About Case

suppose We need a stored procedure that can be called by an application but the user wants to be able sort by either first name or last name. One would be tempted to use dynamic SQL to solve this problem, but we can use CASE to create a dynamic SQL equivalent
CREATE PROCEDURE dbo.getCustomerData @sortby VARCHAR(9), @sortdirection CHAR(4)
AS
SET nocount ON

SELECT customerid, firstname, lastname, statecode, statedescription, totalsales
FROM dbo.Customer
ORDER BY
CASE @sortdirection
WHEN 'asc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
ASC,
CASE @sortdirection
WHEN 'desc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
DESC
GO

EXEC dbo.getCustomerData 'lastname', 'desc'




A final requirement has crossed our desk. We need to modify the stored procedure to search customers by a specific state. If the state is omitted, we should return customers for all states.
ALTER PROCEDURE dbo.getCustomerData @sortby VARCHAR(9), @sortdirection CHAR(4), @statecode VARCHAR(2) = NULL
AS
SET nocount ON

SELECT customerid, firstname, lastname, statecode, statedescription, totalsales
FROM dbo.Customer
WHERE statecode = CASE WHEN @statecode IS NOT NULL THEN @statecode
ELSE statecode
END
ORDER BY
CASE @sortdirection
WHEN 'asc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
ASC,
CASE @sortdirection
WHEN 'desc' THEN
CASE @sortby
WHEN 'firstname' THEN firstname
WHEN 'lastname' THEN lastname
END
END
DESC
GO

EXEC dbo.getCustomerData 'lastname', 'desc', 'MA'

Monday, July 7, 2008

Using Coalesce to Pivot

Using Coalesce to Pivot
If you run the following statement against the AdventureWorks database
SELECT Name
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')

you will come up with a standard result

If you want to pivot the data you could run the following command.
DECLARE @DepartmentName VARCHAR(1000)

SELECT @DepartmentName = COALESCE(@DepartmentName,'') + Name + ','
FROM HumanResources.Department
WHERE (GroupName = 'Executive General and Administration')

SELECT @DepartmentName AS DepartmentNames

and get the result set with comma separated in a single column.

SQL Server Function to Determine a Leap Year

The following scalar function takes in a year and returns a bit flag indicating whether the passed in year is a leap year or not.

create function dbo.fn_IsLeapYear (@year int)
returns bit
as
begin
return(select case datepart(mm, dateadd(dd, 1, cast((cast(@year as varchar(4)) + '0228') as datetime)))
when 2 then 1
else 0
end)
end
go

That's all there is to it! The function takes in the year, appends '0228' to it (for February 28th) and adds a day. If the month of the next day is a 2 (as extracted by the DATEPART function), then we're still in February so it must be a leap year! If not, it is not a leap year.
Here are a few examples:

select dbo.fn_IsLeapYear(1900) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2000) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2007) as 'IsLeapYear?'
select dbo.fn_IsLeapYear(2008) as 'IsLeapYear?'