日期:2014-05-17 浏览次数:20369 次
--if object_id('dbo.CHINA_STR') is not null drop FUNCTION DBO.CHINA_STR
CREATE FUNCTION DBO.CHINA_STR(@S NVARCHAR(100))
RETURNS VARCHAR(100)
AS
BEGIN
WHILE PATINDEX('%[吖-座]%',@S) > 0
SET @S = STUFF(@S,PATINDEX('%[吖-座]%',@S),1,N'')
WHILE PATINDEX('%[a-Z]%',@S) > 0
SET @S=stuff(@S,patindex('%[a-Z]%',@S),1,'')
RETURN @S
END
GO
declare @sql varchar(8000)
set @sql=列名A
select @sql= 'select '+DBO.CHINA_STR(@sql)
exec(@sql)
declare @s varchar(50)
set @s='1个+2桶+3箱+4瓶+8托'
declare @i int
set @i=1
declare @sql varchar(100)
set @sql='select '
while(@s<>'')
begin
if patindex('%[0-9]%',substring(@s,@i,1))=1
set @sql=@sql+substring(@s,@i,1)+'+'
set @s=stuff(@s,@i,1,'')
end
set @sql=left(@sql,len(@sql)-1)
exec(@sql)
--建函數
create function f_getsum(@s nvarchar(100))
returns int
as
begin
declare @temp table(num int)
declare @sum int
declare @sz varchar(10)
set @sz=''
declare @i int
set @i=1
while(@s<>'')
begin
if patindex('%[0-9]%',substring(@s,@i,1))=1
set @sz=@sz+substring(@s,@i,1)
else if(@sz<>'')
begin
insert into @temp select @sz
set @sz=''
end
set @s=stuff(@s,@i,1,'')
end
if(@sz<>'')
insert into @temp select @sz
select @sum=sum(num) from @temp
return @sum
end
--測試
select dbo.f_getsum(num) from
(
select N'1箱+1箱' as num
union all select N'1箱+1箱+1箱+1箱' as num
union all select N'1個+10個+2個' as num
) as a
--結果
2
4
13