2010
Mar 11
Here’s a good tip from Deepak Choudhari of DevX.com


Choosing a Large-Text Data Type for SQL Server Table Columns


What would you do if you needed to store text data in a table column that exceeds 8000 characters? The common choices are the TEXT and NTEXT data types, but these data types are going to be deprecated in the near future.


The solution to this problem is a data type called VARCHAR(MAX), introduced with SQL Server 2005. You can use this data type whenever you want to store text data that varies considerably in length, or that exceeds 8000 characters. The following examples show how to use this data type.


To declare a column of this type in a table, use:


CREATE TABLE MyTable(column1 VARCHAR(MAX), column2 INT … )


To declare a variable of this type in stored procedures or functions, use:


DECLARE @MyVariable VARCHAR(MAX)


This new data type works with the majority of the intrinsic string-manipulation functions, whereas the legacy BLOB types such as TEXT, NTEXT, and IMAGE do not. The new data type is stored in the database in the same exact way, but Microsoft has made some tweaks to the read algorithms for the new types, too.

Efficient Paging Code for MS SQL Server 2005

Posted by on Mar 11th, 2008
2008
Mar 11
As a web developer I often encounter the need to page results for better UI experience.

Normally with an SQL ANSI 92 compliant database engine all you had to do was specify how many rows you wanted returned and how many rows to skip, something like:

SELECT First 10 Skip 10 *
FROM table1
ORDER BY Column1


Which translates to skip 10 rows and then return next 10 rows.

Unfortunately, there was no such thing in MS SQL Server. So after two hours of searching I encountered function called Row_Number.

As per the SQL Book online, the Row_Number() function returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition.

Anyhow, here is how the new query looked like:

SELECT *
FROM  (
   SELECT Row_Number() OVER(ORDER BY Column1) AS Row,
       *
   FROM table1
) WHERE Row Between 10 AND 20
ORDER BY Column1


The SQL was longer but it had same desired effect. Anyhow it’s getting late, hope I was of help.