字元串由幾個單片語成,一般情況之下以空格分隔來計算即可。 實現方法,參考下麵自定義函數: SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- -- Author: Insus.NET -- Create date: 2019-05-13 -- Up ...
字元串由幾個單片語成,一般情況之下以空格分隔來計算即可。
實現方法,參考下麵自定義函數:
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: Insus.NET -- Create date: 2019-05-13 -- Update date: 2019-05-13 -- Description: 計算字元串由幾個單片語成 -- ============================================= CREATE FUNCTION [dbo].[svf_WordCount] ( @InputString NVARCHAR(MAX) ) RETURNS INT AS BEGIN DECLARE @Index INT = 1 DECLARE @CurrentChar CHAR(1) DECLARE @PreviousChar CHAR(1) DECLARE @WordCount INT = 0 WHILE @Index <= LEN(@InputString) BEGIN SET @CurrentChar = SUBSTRING(@InputString, @Index, 1) SET @PreviousChar = SUBSTRING(@InputString, @Index - 1, 1) IF @PreviousChar = ' ' AND @CurrentChar != ' ' SET @WordCount = @WordCount + 1 SET @Index = @Index + 1 END RETURN @WordCount END GOSource Code
舉例演示: