I'm writing a utility script that will take a column from a database table and produce a snipped of javascript code. What I would like is to return a value like "First_Name" and camel case it to "firstName". Is there an easy way to do this in SQL? I'm using T-SQL.
How about this:
CREATE FUNCTION [dbo].[udfCamel]
(
@Name VARCHAR(50)
)
RETURNS varchar(50)
AS
BEGIN
declare @newstring varchar(50)
set @newstring = stuff(replace(@Name, '_', ''), 1, 1, lower(left(@Name, 1)))
RETURN @newstring
END
Then when you execute it:
declare @str varchar(50)
set @str = 'First_Name'
select dbo.udfCamel(@str)
returns: firstName
To transform to "camelCase" (not CamelCase) this should work:
ALTER FUNCTION dbo.camelCase(
@input VARCHAR(8000)
)
RETURNS VARCHAR(8000)
AS
BEGIN
SET @input = LTRIM(RTRIM(@input))
DECLARE
@i INT = 0
,@len INT = LEN(@input)
,@upper BIT = 0
,@output varchar(8000) = ''
,@char NCHAR
,@ascii INT
WHILE @i < @len BEGIN
SELECT
@i = @i + 1
,@char = SUBSTRING(@input, @i, 1)
,@ascii = ASCII(@char)
IF NOT ((@ascii >= 65 AND @ascii <= 90) OR (@ascii >= 97 AND @ascii <= 122) OR (@ascii
>= 48 AND @ascii <= 57)) BEGIN
SET @upper = 1
CONTINUE
END
IF (@upper = 1) SET @output = @output + UPPER(@char)
IF (@upper = 0) SET @output = @output + LOWER(@char)
SET @upper = 0
END
RETURN @output
END
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With