logo
SQL: capitalize first letter only
GiacKhongDaiSu Offline
#1 Đã gửi : 06/11/2015 lúc 08:01:08(UTC)

Danh hiệu: Kê Vương

Gia nhập: 23-01-2011(UTC)
Bài viết: 2,113
Man
Đến từ: HCM

Thanks: 4 times
Được cảm ơn: 300 lần trong 220 bài viết



Dùng hàm Function như sau:

Mã:

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

BEGIN
--Declare Variables
DECLARE @Index INT,
@ResultString NVARCHAR(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
Ai đang xem chủ đề này?
Guest
Bạn không thể tạo chủ đề mới trong diễn đàn này.
Bạn không thể trả lời chủ đề trong diễn đàn này.
Bạn không thể xóa bài của bạn trong diễn đàn này.
Bạn không thể sửa bài của bạn trong diễn đàn này.
Bạn không thể tạo bình chọn trong diễn đàn này.
Bạn không thể bỏ phiếu bình chọn trong diễn đàn này.

Green-Grey Theme Created by Ingo Herbote (WatchersNET.de)
Powered by YAF | YAF © 2003-2010, Yet Another Forum.NET
Thời gian xử lý trang này hết 0.038 giây.