Created
May 14, 2012 23:41
-
-
Save javierguerrero/2698097 to your computer and use it in GitHub Desktop.
Cómo extraer un número desde una cadena en SQL Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE FUNCTION dbo.EXTRACT_YEAR(@periodo AS VARCHAR(max)) | |
RETURNS INT | |
AS | |
BEGIN | |
WHILE PATINDEX('%[^0-9]%', @periodo) > 0 | |
BEGIN | |
SET @periodo = REPLACE(@periodo,SUBSTRING(@periodo,PATINDEX('%[^0-9]%', @periodo),1),'') | |
END | |
RETURN LEFT(@periodo, 4) | |
END | |
/*Cómo usar la función*/ | |
SELECT dbo.EXTRACT_YEAR('Enero - Diciembre 1994') | |
/* | |
DECLARE @periodo varchar(30) | |
SET @periodo = '2008 - I' | |
WHILE PATINDEX('%[^0-9]%', @periodo) > 0 | |
BEGIN | |
SET @periodo = REPLACE(@periodo,SUBSTRING(@periodo,PATINDEX('%[^0-9]%', @periodo),1),'') | |
END | |
select LEFT(@periodo, 4) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Muchas gracias, me fue muy útil.