天天看點

sql 字元串分割求和

功能說明:

要求某個字元串如:1,2,3,4 或者1.11,2.1,4的和

1、函數建立

USE [wqq]
GO
/****** Object:  UserDefinedFunction [dbo].[getSum]    Script Date: 07/17/2013 22:04:05 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--擷取如字元串"1,2,3,4"中以逗号隔開的數組的長度
ALTER FUNCTION [dbo].[getSum]
(
	@str nvarchar(max),--字元串
	@ch nvarchar(100)--分隔符
)
RETURNS decimal(18,2)
AS
BEGIN
	declare @sum decimal(18,2)
	declare @location int --目前位置 循環條件
	declare @start int --記錄開始取字元串的初始位置
	declare @len int [email protected]的長度
	declare @amount decimal(18,2)--暫存數組中的一個值
	
    set @str=ISNULL(@str,'')--如果@str為null那麼設為 空字元串
    
	if(@str='')--如果為空字元串那麼傳回值為null
	begin
		return null
	end
	
	
	--循環取值求和
	set @sum=0
	set @[email protected][email protected]
	set @len=LEN(@ch)
	set @start=1
	set @location=CHARINDEX(@ch,@str)
	if @location=0
	begin
		set @location=LEN(@str)+1
	end
	
	while @location!=0
	begin
		set @amount=SUBSTRING(@str,@start,@[email protected])
		set @[email protected][email protected]
		set @[email protected][email protected]
		set @location=CHARINDEX(@ch,@str,@start)
	end
	return @sum
	
END
           

2、測試

select wqq.dbo.getSum('1.1111****2.0****832389.11','****')
select wqq.dbo.getSum('1.1,2,4',',')
           

其中wqq是資料庫名稱

3、測試結果

sql 字元串分割求和