Next, the string is split, each character is inserted into a table variable, and finally grouped by using GROUP by.
Copy Code code as follows:
Calnumofchtinstr
SET ANSI_NULLS on
Go
SET QUOTED_IDENTIFIER ON
Go
-- =============================================
--Author:Insus.NET
--Create date:2012-02-23
--Description:calculate The number of characters in the string
-- =============================================
CREATE PROCEDURE [dbo]. [Calnumofchtinstr]
(
@Value NVARCHAR (MAX)
)
As
BEGIN
DECLARE @dum TABLE ([Str] NVARCHAR (2))
DECLARE @i int = len (@Value), @j int = len (@Value)
While @i > 0
BEGIN
--The following functions can refer to: http://www.cnblogs.com/insus/archive/2011/06/25/2090231.html
IF [dbo]. [Isinteger] (SUBSTRING (@Value, @i, 1)) = 0
BEGIN
RAISERROR (' Incoming string contains other characters, not exactly a number. ', 16, 1)
Return
End
SET @i = @i-1
End
While @j > 0
BEGIN
INSERT into @dum VALUES (SUBSTRING (@Value, @j, 1))
SET @j = @j-1
End
SELECT [Str],count ([str]) as [Num] from @dum GROUP by [str]
End
Demo:
Copy Code code as follows:
EXECUTE [dbo]. [Calnumofchtinstr] ' 5487554127489423454 '
Results:
The following text is updated on 2012-02-24 09:40
Analyze the above stored procedure, considering the performance problem, it loops the string once, and then loops each character into the table variable once it is judged whether it contains any other characters. The following modifications are only done at this point only once.
Copy Code code as follows:
Calnumofchtinstr
SET ANSI_NULLS on
Go
SET QUOTED_IDENTIFIER ON
Go
-- =============================================
--Author:Insus.NET
--Create date:2012-02-23
--Update date:2012-02-24
--Description:calculate The number of characters in the string
-- =============================================
ALTER PROCEDURE [dbo]. [Calnumofchtinstr]
(
@Value NVARCHAR (MAX)
)
As
BEGIN
DECLARE @dum TABLE ([Str] NVARCHAR (2))
DECLARE @i INT = LEN (@Value)
While @i > 0
BEGIN
INSERT into @dum VALUES (SUBSTRING (@Value, @i, 1))
SET @i = @i-1
End
--The following functions can refer to: http://www.cnblogs.com/insus/archive/2011/06/25/2090231.html
IF EXISTS (SELECT top 1 1 from @dum WHERE [dbo].[ Isinteger] ([Str]) = 0)
BEGIN
RAISERROR (' Incoming string contains other characters, not exactly a number. ', 16, 1)
Return
End
SELECT [Str],count ([str]) as [Num] from @dum GROUP by [str]
End
The following items were added at 2012-04-29 10:44:
If you want to refer to the C # version http://www.jb51.net/article/30211.htm