SQL Server 2008 - Worth the Wait
Here's another scenario! How about getting just the numbers from a given string? Remember those cell phones pulling out the numbers from SMS/Text messages? :-) Of course, this problem can be solved easily using a procedural approach by looping through the string from starting to the end and discarding non-numeric characters. Performance difference between these two approaches should be minimal. I haven't actually tried benchmarking, but will update this article if and when I do. Anyway, here's the code:
DECLARE @input varchar(100), @output varchar(100), @len smallintSET @input = 'My Number is: 0771 543 2360'SET @output = ''SET @len = LEN(@input)SELECT @output = @output + ValFROM(SELECT TOP 100 PERCENT Number, SUBSTRING(@input, Number, 1) AS ValFROM dbo.Numbers (NOLOCK)WHERE Number <= @lenORDER BY Number) AS DerivedWHERE Val LIKE '[0-9]' SELECT @input AS 'Original string',@output AS 'Extracted numbers'
If you are running SQL Server 2000, the above scripts can be converted to handy User Defined Functions (UDF). I said "handy" because, UDFs can be used in a lot of places like column list, WHERE clause of a SELECT statement. Here are the User Defined Function scripts:
User Defined Function 1: SortString()
IF EXISTS(SELECT 1FROM INFORMATION_SCHEMA.ROUTINESWHERE ROUTINE_NAME = 'SortString'AND ROUTINE_SCHEMA = 'dbo'AND ROUTINE_TYPE = 'FUNCTION')BEGINDROP FUNCTION dbo.SortStringENDGOCREATE FUNCTION dbo.SortString(@input varchar(8000))RETURNS varchar(8000)ASBEGINDECLARE @output varchar(8000), @len smallintSET @output = ''SET @len = LEN(@input)SELECT @output = @output + Val FROM (SELECT TOP 100 PERCENT SUBSTRING(@input, Number, 1) AS ValFROM dbo.Numbers (NOLOCK)WHERE Number <= @lenORDER BY Val) AS DerivedRETURN @outputENDGOSELECT dbo.SortString('911Abcdzyxfghjie999') AS 'Sorted string'GO
User Defined Function 2: ExtractUniqueChars()
IF EXISTS(SELECT 1FROM INFORMATION_SCHEMA.ROUTINESWHERE ROUTINE_NAME = 'ExtractUniqueChars'AND ROUTINE_SCHEMA = 'dbo'AND ROUTINE_TYPE = 'FUNCTION')BEGINDROP FUNCTION dbo.ExtractUniqueCharsENDGOCREATE FUNCTION dbo.ExtractUniqueChars(@input varchar(8000))RETURNS varchar(8000)ASBEGINDECLARE @output varchar(8000), @len smallintSET @output = ''SET @len = LEN(@input)SELECT @output = @output + ValFROM(SELECT DISTINCT TOP 100 PERCENT SUBSTRING(@input, Number, 1) AS ValFROM dbo.Numbers (NOLOCK)WHERE Number <= @lenORDER BY Val) AS DerivedRETURN @outputENDGOSELECT dbo.ExtractUniqueChars('cba abc bac') AS 'Unique characters (Sorted)'GO