Sqlserver
 sql >> Cơ Sở Dữ Liệu >  >> RDS >> Sqlserver

SQL:chỉ viết hoa chữ cái đầu tiên

Bạn đang yêu cầu đổi tên chính cột hoặc viết hoa dữ liệu bên trong cột? Nếu dữ liệu của nó bạn đã thay đổi, thì hãy sử dụng cái này:

UPDATE [yourtable]
SET word=UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word)))

Nếu bạn chỉ muốn thay đổi nó chỉ để hiển thị và không cần dữ liệu thực tế trong bảng để thay đổi:

SELECT UPPER(LEFT(word,1))+LOWER(SUBSTRING(word,2,LEN(word))) FROM [yourtable]

Hy vọng điều này sẽ hữu ích.

CHỈNH SỬA:Tôi đã biết về dấu '-' vì vậy, đây là nỗ lực của tôi để giải quyết vấn đề này trong một hàm.

CREATE FUNCTION [dbo].[CapitalizeFirstLetter]
(
--string need to format
@string VARCHAR(200)--increase the variable size depending on your needs.
)
RETURNS VARCHAR(200)
AS

BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString VARCHAR(200)--result string size should equal to the @string variable size
--Initialize the variables
SET @Index = 1
SET @ResultString = ''
--Run the Loop until END of the string

WHILE (@Index <LEN(@string)+1)
BEGIN
IF (@Index = 1)--first letter of the string
BEGIN
--make the first letter capital
SET @ResultString =
@ResultString + UPPER(SUBSTRING(@string, @Index, 1))
SET @Index = @Index+ 1--increase the index
END

-- IF the previous character is space or '-' or next character is '-'

ELSE IF ((SUBSTRING(@string, @Index-1, 1) =' 'or SUBSTRING(@string, @Index-1, 1) ='-' or SUBSTRING(@string, @Index+1, 1) ='-') and @Index+1 <> LEN(@string))
BEGIN
--make the letter capital
SET
@ResultString = @ResultString + UPPER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--increase the index
END
ELSE-- all others
BEGIN
-- make the letter simple
SET
@ResultString = @ResultString + LOWER(SUBSTRING(@string,@Index, 1))
SET
@Index = @Index +1--incerase the index
END
END--END of the loop

IF (@@ERROR
<> 0)-- any error occur return the sEND string
BEGIN
SET
@ResultString = @string
END
-- IF no error found return the new string
RETURN @ResultString
END

Vì vậy, sau đó mã sẽ là:

UPDATE [yourtable]
SET word=dbo.CapitalizeFirstLetter([STRING TO GO HERE])


  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. Tạo bảng tạm thời trong SQL Server

  2. Độ bền bị trễ trong SQL Server 2014

  3. Sử dụng OBJECTPROPERTY () để Tìm hiểu xem một Đối tượng có phải là Ràng buộc KIỂM TRA trong SQL Server hay không

  4. Cách tạo câu lệnh chèn từ tệp văn bản cho bảng SQL Server trong SQL Server - Hướng dẫn sử dụng SQL Server / TSQL Phần 106

  5. Làm thế nào để tìm các hàng liên tiếp dựa trên giá trị của một cột?