Posts

Showing posts from February, 2013

Separate camel case String

Below is the query to separate camel case string and removing first lower part from the string on condition IF @skipFirstLowerPart = 0 means skip first lower part from the string and                  IF @skipFirstLowerPart = 1 then do not skip first lower part from the string DECLARE @str VARCHAR ( 100 ) = 'txtFirstName' DECLARE @skipFirstLowerPart INT = 0 -- 0 yes 1 no DECLARE @len INT = LEN ( @str ), @ptr INT = 1 , @chk INT = 0 DECLARE @newstr VARCHAR ( 100 ) = '' WHILE @len > 0 BEGIN       DECLARE @char CHAR ( 1 ) = SUBSTRING ( @str , @ptr , @ptr + 1 )             IF @skipFirstLowerPart = 0       BEGIN             IF ( CONVERT ( VARBINARY ( 128 ), @char ) = CONVERT ( VARBINARY ( 128 ), LOWER ( @char ))) AND ( @chk = 0 )             BEGIN                   SET @char = ''             END       END       IF CONVERT ( VARBINARY ( 128 ), @char ) <> CONVERT ( VARBINARY ( 1

Extract Numbers OR Characters From String

Below is the query to extract numbers or integers from an alphanumeric string. PATINDEX () and STUFF() and a WHILE loop is used to get the result. DECLARE @str VARCHAR ( 100 ) = 'hello123testing456' DECLARE @hasPat INT = PATINDEX ( '%[a-z]%' , @str ) WHILE @hasPat > 0 BEGIN       SET @str = STUFF ( @str , @hasPat , 1 , '' )       SET @hasPat = PATINDEX ( '%[a-z]%' , @str ) END SELECT @str AS NumOnly Result: NumOnly -------------------------------- 123456 The above code can be modified to extract characters from the alphanumeric string by just changing the pattern inside PATINDEX() function DECLARE @str VARCHAR ( 100 ) = 'hello123testing456' DECLARE @hasPat INT = PATINDEX ( '%[0-9]%' , @str ) WHILE @hasPat > 0 BEGIN       SET @str = STUFF ( @str , @hasPat , 1 , '' )       SET @hasPat = PATINDEX ( '%[0-9]%' , @str ) END