Thursday, February 12, 2015

Get Integer from a String using MS SQL Server

Execute the following:

DECLARE @strAlphaNumeric VARCHAR(256)

SET @strAlphaNumeric = 'Hello2 World'

DECLARE @intAlpha INT

SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric)



BEGIN
 
WHILE @intAlpha > 0



BEGIN
 
SET @strAlphaNumeric = STUFF(@strAlphaNumeric, @intAlpha, 1, '' )

SET @intAlpha = PATINDEX('%[^0-9]%', @strAlphaNumeric )



END

END
 
SELECT ISNULL(@strAlphaNumeric,0)
 
 


OUTPUT:
2

Get Last Character/s from a String in MS SQL Server

Execute the following:

DECLARE @varTmp NVARCHAR(20)

SET @varTmp = 'Hello World'

SELECT RIGHT(@varTmp,5)



OUTPUT:

World


Note: Same thing when trying to get only the first set of characters.

SELECT LEFT(@varTmp,5)

OUTPUT:

Hello