Last active
August 17, 2017 18:00
-
-
Save RichardHan/3ce2913190b7faa9cc6a5e338323b607 to your computer and use it in GitHub Desktop.
[SQL] Function - Underscore Case
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
-- select dbo.fn_UnderscoreCase('HelloWorld') | |
-- | |
-- Input HelloWorld | |
-- | |
-- Output hello_world | |
-- | |
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'fn' AND name = | |
'fn_UnderscoreCase') | |
DROP function fn_UnderscoreCase | |
GO | |
CREATE function fn_UnderscoreCase (@x varchar(500)) RETURNS varchar(500) | |
AS | |
BEGIN | |
DECLARE @y varchar(500) | |
, @z int | |
, @i int | |
, @a varchar(2) | |
, @b int | |
, @c int | |
, @d int | |
SELECT @y = '' | |
, @z = datalength(@x) | |
, @i = 1 | |
WHILE @i <= @z | |
BEGIN SELECT @a = substring(@x, @i, 1) | |
SET @b = ascii(@a) | |
IF @i > 1 | |
BEGIN SELECT @c = ascii(substring(@x, @i - 1, 1)) | |
, @d = ascii(substring(@x, @i + 1, 1)) | |
IF @b BETWEEN 65 AND 90 -- Uppercase characters | |
BEGIN IF @c NOT BETWEEN 65 AND 90 AND @c NOT IN (36, 45, 95) | |
SET @y = @y + ' ' | |
IF @d NOT BETWEEN 65 AND 90 AND @d NOT IN (36, 45, 95) | |
SET @y = @y + ' ' | |
END | |
ELSE IF @b = 36 -- the "$" | |
SET @y = @y + ' ' | |
ELSE IF @b = 46 -- the "." | |
BEGIN IF @c NOT BETWEEN 48 AND 57 | |
AND @d NOT BETWEEN 48 AND 57 | |
BEGIN IF @d NOT BETWEEN 48 AND 57 | |
SET @a = @a + ' ' | |
END | |
END | |
ELSE IF @b BETWEEN 48 AND 57 -- Numbers | |
BEGIN IF @c NOT BETWEEN 48 AND 57 AND @c NOT IN (36, 46) | |
-- OR ascii(substring(@x, @i + 1, 1)) NOT BETWEEN 48 AND 57 | |
SET @y = @y + ' ' | |
END | |
END | |
SELECT @y = @y + @a | |
, @i = @i + 1 | |
END | |
SELECT @y = replace(LOWER(ltrim(replace(replace(@y, ' ', ' '), ' ', ' '))),' ','_') | |
RETURN (@y) | |
END | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment