1、需求如下
实现字符串 '0.1±0.013mm(不含铜厚)' 转换为 '0.100±0.013'
实现字符串 '0.10±0.013mm(不含铜厚)' 转换为 '0.100±0.013'
实现字符串 '0.102±0.013mm(1035*2不含铜厚)' 转换为 '0.100±0.013'
/*
实现字符串 '0.1±0.013mm(不含铜厚)' 转换为 '0.100±0.013'
实现字符串 '0.10±0.013mm(不含铜厚)' 转换为 '0.100±0.013'
实现字符串 '0.102±0.013mm(1035*2不含铜厚)' 转换为 '0.100±0.013'
*/
2、创建自定义函数
create function fn_GetParamValue(@ParamValue VARCHAR(128))
RETURNS varchar(16)
AS
BEGIN
DECLARE @temp_result VARCHAR(128);
DECLARE @result VARCHAR(128);
DECLARE @last_temp VARCHAR(128);
DECLARE @lastpart_value VARCHAR(128);
SET @last_temp=ISNULL(SUBSTRING(REPLACE(@ParamValue,' ',''),1,CHARINDEX('mm',REPLACE(@ParamValue,' ',''))-1),0)
SET @lastpart_value=SUBSTRING(@last_temp,CHARINDEX('±',@last_temp)+1,LEN(@last_temp))
SET @temp_result=SUBSTRING(ISNULL(SUBSTRING(REPLACE(@ParamValue,' ',''),1,CHARINDEX('mm',REPLACE(@ParamValue,' ',''))-1),0),1,CHARINDEX('±',REPLACE(@ParamValue,' ',''))-1)
IF LEN(@temp_result)=3
BEGIN
SET @result=SUBSTRING(@temp_result,1,2)+RIGHT(SUBSTRING(@temp_result,3,1)+'00',3)
END
ELSE IF LEN(@temp_result)=4
BEGIN
SET @result=SUBSTRING(@temp_result,1,2)+RIGHT(SUBSTRING(@temp_result,3,2)+'0',3)
END
ELSE
BEGIN
SET @result=LTRIM(RTRIM(@temp_result))
END
RETURN @result+'±'+@lastpart_value
END;
3、查询调用创建的函数
SELECT dbo.fn_GetParamValue('0.1±0.013mm(不含铜厚)') value_1,
dbo.fn_GetParamValue('0.10±0.013mm(不含铜厚)') value_2,
dbo.fn_GetParamValue('0.102±0.013mm(1035*2不含铜厚)') value_3
GO
value_1 value_2 value_3
---------------- ---------------- ----------------
0.100±0.013 0.100±0.013 0.102±0.013
(1 行受影响)