我正在编写一个实用程序脚本,它将从数据库表中获取一列并生成一段 javascript 代码。我想要的是返回一个像“First_Name”这样的值并将它的骆驼大小写为“firstName”。有没有一种简单的方法可以在 SQL 中做到这一点?我正在使用 T-SQL。
问问题
8979 次
4 回答
4
这个怎么样:
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
然后当你执行它时:
declare @str varchar(50)
set @str = 'First_Name'
select dbo.udfCamel(@str)
返回:firstName
于 2012-08-13T19:42:02.507 回答
2
要转换为“camelCase”(不是 CamelCase),这应该有效:
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
于 2019-01-21T18:34:17.370 回答
1
您可以使用标量函数返回骆驼大小写。这也将处理小写场景。这是一个可能对您有用的示例:
DECLARE @MyText VARCHAR(MAX)
SET @MyText = 'Convert_This_to_Camel_Case'
WHILE(CHARINDEX('_',@MyText) > 0)
BEGIN
SET @MyText = REPLACE(@MyText,'_' +SUBSTRING(@MyText,(CHARINDEX('_',@MyText) + 1),1), UPPER(SUBSTRING(@MyText,(CHARINDEX('_',@MyText) + 1),1)))
END
SELECT LOWER(SUBSTRING(@MyText,1,1))+ SUBSTRING(@MyText, 2, LEN(@MyText) -1)
于 2012-08-13T19:43:15.377 回答
0
我只是碰巧完成了类似的工作并且仍然启动了 SQL,所以我想我会在这个线程上测试选定的答案,但我并没有完全得到我想要的结果,所以我想我会提供另一种选择
//dbo.udfCamel is script above set as answer
//dbo.CamelCase is script being added below
SELECT dbo.CamelCase('microSoft sql server'), dbo.udfCamel('microSoft sql server')
//results:
// dbo_CamelCase dbo_udfCamel
// microsoftSqlServer microSoft sql server
CREATE FUNCTION [dbo].[CamelCase]
(@Str varchar(8000))
RETURNS varchar(8000) AS
BEGIN
DECLARE @Result varchar(2000)
SET @Str = LOWER(@Str) + ' '
SET @Result = ''
WHILE 1=1
BEGIN
IF PATINDEX('% %',@Str) = 0 BREAK
SET @Result = @Result + UPPER(Left(@Str,1))+ SubString (@Str,2,CharIndex(' ',@Str)-1)
SET @Str = SubString(@Str, CharIndex(' ',@Str)+1,Len(@Str))
END
SET @Result = Left(@Result,Len(@Result))
SET @Result = REPLACE(@Result, ' ', '')
SET @Result = LOWER(SUBSTRING(@Result, 1, 1)) + SUBSTRING(@Result, 2, LEN(@Result)-1)
RETURN @Result
END
于 2020-11-20T17:28:26.760 回答