在SQL Server中,将string中每个单词的首字母大写的最佳方法是什么?
在SQL Server中,将string中每个单词的首字母大写的最佳方法是什么?
从http://www.sql-server-helper.com/functions/initcap.aspx
CREATE FUNCTION [dbo].[InitCap] ( @InputString varchar(4000) ) RETURNS VARCHAR(4000) AS BEGIN DECLARE @Index INT DECLARE @Char CHAR(1) DECLARE @PrevChar CHAR(1) DECLARE @OutputString VARCHAR(255) SET @OutputString = LOWER(@InputString) SET @Index = 1 WHILE @Index <= LEN(@InputString) BEGIN SET @Char = SUBSTRING(@InputString, @Index, 1) SET @PrevChar = CASE WHEN @Index = 1 THEN ' ' ELSE SUBSTRING(@InputString, @Index - 1, 1) END IF @PrevChar IN (' ', ';', ':', '!', '?', ',', '.', '_', '-', '/', '&', '''', '(') BEGIN IF @PrevChar != '''' OR UPPER(@Char) != 'S' SET @OutputString = STUFF(@OutputString, @Index, 1, UPPER(@Char)) END SET @Index = @Index + 1 END RETURN @OutputString END GO
在这里有一个更简单/更小的(但是如果任何行没有空格,“无效的长度parameter passing给RIGHT函数”不起作用)。
我已经使用了一段时间的变化是:
CREATE FUNCTION [widget].[properCase](@string varchar(8000)) RETURNS varchar(8000) AS BEGIN SET @string = LOWER(@string) DECLARE @i INT SET @i = ASCII('a') WHILE @i <= ASCII('z') BEGIN SET @string = REPLACE( @string, ' ' + CHAR(@i), ' ' + CHAR(@i-32)) SET @i = @i + 1 END SET @string = CHAR(ASCII(LEFT(@string, 1))-32) + RIGHT(@string, LEN(@string)-1) RETURN @string END
如果您想要,您可以轻松修改以处理除空格之外的项目之后的字符。
没有使用循环的另一种解决scheme – 使用recursionCTE的纯集合方法
create function [dbo].InitCap (@value varchar(max)) returns varchar(max) as begin declare @separator char(1) = ' ', @result varchar(max) = ''; with r as ( select value, cast(null as varchar(max)) [x], cast('' as varchar(max)) [char], 0 [no] from (select rtrim(cast(@value as varchar(max))) [value]) as j union all select right(value, len(value)-case charindex(@separator, value) when 0 then len(value) else charindex(@separator, value) end) [value] , left(r.[value], case charindex(@separator, r.value) when 0 then len(r.value) else abs(charindex(@separator, r.[value])-1) end ) [x] , left(r.[value], 1) , [no] + 1 [no] from r where value > '') select @result = @result + case when ascii([char]) between 97 and 122 then stuff(x, 1, 1, char(ascii([char])-32)) else x end + @separator from r where x is not null; set @result = rtrim(@result); return @result; end
这是最简单的一行代码。
select LEFT(column, 1)+ lower(RIGHT(column, len(column)-1) ) from [tablename]
作为一个表值函数:
CREATE FUNCTION dbo.InitCap(@v AS VARCHAR(MAX)) RETURNS TABLE AS RETURN WITH a AS ( SELECT ( SELECT UPPER(LEFT(value, 1)) + LOWER(SUBSTRING(value, 2, LEN(value))) AS 'data()' FROM string_split(@v, ' ') FOR XML PATH (''), TYPE) ret) SELECT CAST(a.ret AS varchar(MAX)) ret from a GO
请注意, string_split
需要COMPATIBILITY_LEVEL
130。
你应该试试这个
Select INITCAP(column_name) from table_name;
这将大写所提到的属性条目的第一个字母。