我们有一串字符串,比如:
DECLARE @Source VARCHAR(MAX)= ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ‘
现想把它反转显示:
ZYXWVUTSRQPONMLKJIHGFEDCBA
此时,你可以写一个方法来处理:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-16 -- Update date: 2019-05-16 -- Description: 反转字符 CREATE FUNCTION [dbo].[svf_ReverseString] ( @Source VARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @Destination VARCHAR(MAX) = ‘‘ WHILE LEN(@Source) > 0 BEGIN IF LEN(@Source) = 0 BEGIN SET @Destination = @Source + @Destination SET @Source = ‘‘ END ELSE BEGIN SET @Destination = SUBSTRING(@Source, 1, 1) + @Destination SET @Source = SUBSTRING(@Source, 2, LEN(@Source)) END END RETURN @Destination END GO
Source Code
举例运行上面的方法:
哈哈,一切都是白忙,因为Microsoft 已经提供有一个现型的方法REVERSE:
以上不管是哪一个方法,对下面这种情况进行反转,不知是否OK? 字符串以空格为单词进行反转。
因此,得写另外一个方法来处理:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-16 -- Update date: 2019-05-16 -- Description: 反转函数 CREATE FUNCTION [dbo].[svf_Reverse] ( @Source VARCHAR(MAX) ) RETURNS NVARCHAR(MAX) AS BEGIN DECLARE @Destination VARCHAR(MAX) = ‘‘ WHILE LEN(@Source) > 0 BEGIN IF CHARINDEX(‘ ‘, @Source) > 0 BEGIN SET @Destination = SUBSTRING(@Source, 0, CHARINDEX(‘ ‘, @Source)) + ‘ ‘ + @Destination SET @Source = LTRIM(RTRIM(SUBSTRING(@Source, CHARINDEX(‘ ‘, @Source) + 1, LEN(@Source)))) END ELSE BEGIN SET @Destination = @Source + ‘ ‘ + @Destination SET @Source = ‘‘ END END RETURN @Destination END GO
Source Code
原文地址:https://www.cnblogs.com/insus/p/10878806.html
时间: 2024-10-18 10:25:17