如何使用t-sql命令将数据更新为大写首字母?

cet*_*int 19 t-sql sql-server uppercase sql-update

我的数据库上有一张表.我的表名是"公司".我想将数据"company_name"更改为大写首字母.例如;

"ABC公司"

"DEF PLASTICITY"

"Abc公司"

"可塑性"

我知道我应该使用"UPDATE"命令.但是怎么样?谢谢你的帮助!

(CONCAT不起作用)

mr_*_*air 27

SQL Server没有Initcap像oracle 这样的函数.

您可以为Initcap创建UDF.

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
Run Code Online (Sandbox Code Playgroud)

检查UDF是否正常工作

select [dbo].[InitCap] ('stackoverflow com');

Stackoverflow Com
Run Code Online (Sandbox Code Playgroud)

你可以这样更新你的表

update table
set column=[dbo].[InitCap](column);
Run Code Online (Sandbox Code Playgroud)

  • 这太棒了!节省了我很多时间!谢谢! (3认同)

And*_*mar 9

update  YourTable
set     company_name = upper(substring(company_name,1,1)) + 
            lower(substring(company_name, 2, len(company_name)-1))
where   len(company_name) > 0
Run Code Online (Sandbox Code Playgroud)

SQL Fiddle的实例.