I have following lines of code in my user-defined function :
declare @annualStr varchar(30)
declare @annual float
begin try
set @annualStr = dbo.GetXMLValues(@businessId,@id)
set @annual = convert(float,isnull(@annualStr,'0'))
end try
begin catch
set @annual = 0
end catch
The value comes from dbo.GetXMLValues
may be a varchar
value so I need to use try catch block to convert value into float
..
But it throws an error saying.. it is invalid to use try catch blocks in UDF
Why?? And what to do to convert varchar
value to float
when it is unknown
Updated based on comments.
SET @annualstr = dbo.GetXMLValues(@businessId,@id);
IF @annualstr NOT LIKE '%[^0-9.]%' AND @annualstr NOT LIKE '%.%.%'
BEGIN
SET @annual = Cast(@annualstr As float);
END;
SET @annual = Coalesce(@annual, 0);
Incidentally, if you're using SQL 2012+ Then you can use the new Try_Cast()
function
SET @annualStr = dbo.GetXMLValues(@businessId,@id);
SET @annual = Coalesce(Try_Cast(@annualStr As float), 0);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.