Home > SQL Server Tips > Database Management and Administration > User-defined functions to generate and apply a table of sequence numbers
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

DATABASE MANAGEMENT AND ADMINISTRATION

User-defined functions to generate and apply a table of sequence numbers


Brian Walker, Contributor
04.05.2005
Rating: -3.71- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


A table of sequence numbers consists of N rows with each row containing a unique integer value from 1 through N. In some cases it may be more convenient to have the values X through Y where Y-X equals N-1. A table of sequence numbers can be very useful for a variety of purposes. See Listing 1 for a short user-defined function that returns such a table. Of course, similar code can be included within a stored procedure for SQL Server 7 which does not have user-defined functions.

A table of sequence numbers is often involved in a CROSS JOIN with a table of working data. The result set contains a row for every combination of working data and sequence number. This method can be used to replicate the rows of the working data. All rows are replicated N times by default, but a WHERE clause can selectively replicate specific rows in different quantities. For example, if table Address contains addresses for mailing labels the following query would produce three labels for addresses in Nebraska/Kansas/Oklahoma and six labels for all other addresses.

SELECT * FROM Address CROSS JOIN dbo.udfGetSequence(1,6) WHERE Number < CASE State WHEN 'NE' THEN 4 WHEN 'KS' THEN 4 
WHEN 'OK' THEN 4 ELSE 7 END

Here's another way to get the same result.

SELECT * FROM Address, dbo.udfGetSequence(1,6) WHERE State NOT IN ('NE','KS','OK') OR Number < 4 

A table of sequence numbers can also be used as an index into a string value to provide a set-based approach to some common string manipulations. Listing 2 is a user-defined function that counts the number of times one string is found within another string. Listing 3 is a user-defined function that parses a delimited string into individual elements. Both of these functions use the earlier function to generate a table of sequence numbers. Here are some example uses of the two functions.


DECLARE @S varchar(2000)

SET @S = 'football basketball baseball hockey soccer volleyball golf tennis'

SELECT dbo.udfCountString(@S,'ball')

This returns the value 4.

DECLARE @S varchar(2000)

SET @S = 'This fine line is a baseline for the incline of the main line.'

SELECT dbo.udfCountString(@S,'[ ]line[;,.!? ]')

This returns the value 2.

DECLARE @S varchar(2000)

SET @S = '1,12,123,1234,ABCD,ABC,AB,A,*'

SELECT * FROM dbo.udfParseString(@S,',')

This returns a table of nine rows with each one containing an index, an offset, and a string.
1    1   1
2    3   12
3    6   123
4   10   1234
5   15   ABCD
6   20   ABC
7   24   AB
8   27   A
9   29   *

I hope these functions are useful for you and/or help you come up with creative ways to use a table of sequence numbers.

Editor's Note: If you would like to receive similar tips on SQL Server administration and development, be sure to subscribe to the SQL Server Adviser newsletter. Sign up now!


Brian Walker is a Senior Database Architect in an IS department that uses SQL Server 2000 and the .NET Framework. He has over 25 years of experience in the IT industry with the last several years focused on databases and SQL Server. Brian is a software developer, database developer, database administrator, and database consultant. He develops utility software as a hobby, including a large collection of SQL Server utilities.

Rate this Tip
To rate tips, you must be a member of SearchSQLServer.com.
Register now to start rating these tips. Log in if you are already a member.


Submit a Tip




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



RELATED CONTENT
Database Management and Administration
Using traces in SQL Server Profiler
Meet compliance requirements with improved database security practices
Hardening the network and OS for SQL Server security
Securing the server and database in SQL Server
How SQL Server 2008 components impact SharePoint implementations
Troubleshooting Distributed Transaction Coordinator errors in SQL Server
Achieving high availability and disaster recovery with SharePoint databases
Clearing the Windows page file and its effect on server performance
Deploying a SQL Server virtual appliance for Microsoft Hyper-V
How to create SQL Server virtual appliances for Hyper-V

SQL/Transact SQL (T-SQL)
Using DELETE and TRUNCATE TABLE statements to delete data in SQL Server
SQL language crash course (just enough to be dangerous)
Working with IntelliSense in SQL Server 2008 Management Studio
SQL Server Mailbag: Stored procedures, triggers and SSRS reports
Working with sparse columns in SQL Server 2008
Determining the source of full transaction logs in SQL Server
New GROUP BY option provides better data control in SQL Server 2008
Using the OPENROWSET function in SQL Server
Loading data files with SQL Server's BULK INSERT statement
Importing and exporting bulk data with SQL Server's bcp utility
SQL/Transact SQL (T-SQL) Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
ACID  (SearchSQLServer.com)
Collaboration Data Objects  (SearchSQLServer.com)
commit  (SearchSQLServer.com)
container  (SearchSQLServer.com)
DAO  (SearchSQLServer.com)
fetch  (SearchSQLServer.com)
OLE DB  (SearchSQLServer.com)
query  (SearchSQLServer.com)
SQL  (SearchSQLServer.com)
T-SQL  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



SQL Server Development - .NET, C#, T-SQL, Visual Basic
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts