Thursday, December 9, 2010

Try order the text in int form in MSSQL

seems mssql does not have anything try catch situation
when we want to sort a string column containing integer / double

e.g.
If we sort, 1, 5, 23. it will becomes
1
23
5

however, we can perform that using Convert(column, int). But ..... if there is a row which is a non numeric integer, then a error will be happened....

To solve this, we muse use a user defined functions...... 

CREATE FUNCTION dbo.UDF_ParseAlphaChars
(
@string VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
DECLARE
@IncorrectCharLoc SMALLINT
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
WHILE @IncorrectCharLoc > 0
BEGIN
SET
@string = STUFF(@string, @IncorrectCharLoc, 1, '')
SET @IncorrectCharLoc = PATINDEX('%[^0-9A-Za-z]%', @string)
END
SET
@string = @string
RETURN @string
END
GO

—-Test
SELECT dbo.UDF_ParseAlphaChars('ABC”_I+{D[]}4|:e;””5,<.F>/?6')
GO


modify the function and you may archive this.

Reference: http://blog.sqlauthority.com/2007/05/13/sql-server-udf-function-to-parse-alphanumeric-characters-from-string/

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home