删除2个单词之间的间距

时间:2014-08-08 07:37:24

标签: sql sql-server replace trim

我有一个包含名字和第二名的列。现在我想创建一个函数,删除名字和姓氏之间的所有空格,并将第一个字母作为大写字母跟随小写字母。

例如,如果用户输入..

muKesH          AmBanI

然后我将输出作为

Mukesh Ambani

使用MS SQL服务器只有一个空格是第一个字母Capital。

4 个答案:

答案 0 :(得分:2)

请尝试:

declare @var nvarchar(500)='muKesH    AmBanI'

select 
    STUFF(FN, 1, 1, UPPER(LEFT(FN, 1)))+' '+
    STUFF(LN, 1, 1, UPPER(LEFT(LN, 1)))
FROM(
    select 
        LOWER(SUBSTRING(@var, 1, charindex(' ', @var)-1)) FN,
        LOWER(LTRIM(SUBSTRING(@var, charindex(' ', @var), 500))) LN
)x

AS功能

CREATE FUNCTION  FormatString(@text varchar(100))
RETURNS varchar(100)
AS 
BEGIN

    SET @text=@text+' '

    SELECT @text=
        STUFF(FN, 1, 1, UPPER(LEFT(FN, 1)))+' '+
        ISNULL(STUFF(LN, 1, 1, UPPER(LEFT(LN, 1))), '')
    FROM(
        SELECT 
            LOWER(SUBSTRING(@text, 1, charindex(' ', @text)-1)) FN,
            LOWER(RTRIM(LTRIM(SUBSTRING(@text, charindex(' ', @text), 500)))) LN
    )x

RETURN @text
END

答案 1 :(得分:2)

最好的解决方案是构建一个功能。经过在线操作的一些灵感,我根据您的查询进行了调整;

CREATE FUNCTION  FormatString(@text varchar(100))
RETURNS varchar(100)
AS 
declare @counter int, 
        @length int,
        @char char(1),
        @textnew varchar(4000)

    ' @text = 'muKesH          AmBanI'
    set @text       = rtrim(@text)
    set @text       = lower(@text)
    set @length     = len(@text)
    set @counter    = 1

    set @text = upper(left(@text, 1) ) + right(@text, @length - 1) 

    while @counter <> @length --+ 1
    begin
        select @char = substring(@text, @counter, 1)

        IF @char = space(1)  or @char =  '_' or @char = ','  or @char = '.' or @char = '\'
 or @char = '/' or @char = '(' or @char = ')'
        begin
            set @textnew = left(@text, @counter)  + upper(substring(@text, 
@counter+1, 1)) + right(@text, (@length - @counter) - 1)
            set @text    = @textnew
        end

        set @counter = @counter + 1
    end

    return replace(replace(replace(@text,' ','<>'),'><',''),'<>',' ')

END

答案 2 :(得分:1)

根据输出修改查询

DECLARE @t varchar(50)
SELECT @t = 'mukesh          AmBanI'
SELECT UPPER(LEFT(@t,1))+ SUBSTRING(REPLACE(REPLACE(RTRIM(LTRIM(@t)),'  ',' '),'  ',''),2,5)+' '+
LEFT(LTRIM(REVERSE(LEFT(REVERSE(@t),PATINDEX('% %',@t )))),1)+LOWER(SUBSTRING(LTRIM(REVERSE(LEFT(REVERSE(@t),PATINDEX('% %',@t )))),2,5))

答案 3 :(得分:0)

试试这个:

DECLARE @Name VARCHAR(100) = 'muKesH          AmBanI'
DECLARE @Output VARCHAR(100)
SET @Output = LOWER(STUFF(@Name, CHARINDEX(' ',@Name), LEN(@Name)-CHARINDEX(' ',REVERSE(@Name))+1-CHARINDEX(' ',@Name)+1,' '))
SET @Output = STUFF(@Output, CHARINDEX(' ',@Output)+1, 1, UPPER(SUBSTRING(@Output,CHARINDEX(' ',@Output)+1,1)))
SET @Output = UPPER(LEFT(@Output, 1)) + RIGHT(@Output, LEN(@Output)-1)

SELECT @Output