Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

TRY_CONVERT for sql server 2005

$
0
0

hi, experts, I found a function from sql server 2012. try_convert

SELECT 
    CASE WHEN TRY_CONVERT(float, 'test') IS NULL 
    THEN 'Cast failed'
    ELSE 'Cast succeeded'
END AS Result;

can solve what I need. 

however, my company sql server is 2005 sp3. there is no try_convert function.

I have written user defined function myself.

CREATE FUNCTION TryCastInt(@inputStr nvarchar(max))
RETURNS int 
AS 
BEGIN
    DECLARE @ret int;
	set @ret = -999999
    BEGIN TRY
		select @ret = cast (@inputStr as int) 
	END TRY
	BEGIN CATCH
		 set @ret  = -999999
	END CATCH
    RETURN @ret;
END;

but it returns error when I run this create function sql.

Msg 443, Level 16, State 14, Procedure TryCastInt, Line 9
Invalid use of side-effecting or time-dependent operator in 'BEGIN TRY' within a function.
Msg 443, Level 16, State 14, Procedure TryCastInt, Line 11
Invalid use of side-effecting or time-dependent operator in 'END TRY' within a function.
Msg 443, Level 16, State 14, Procedure TryCastInt, Line 12
Invalid use of side-effecting or time-dependent operator in 'BEGIN CATCH' within a function.
Msg 443, Level 16, State 14, Procedure TryCastInt, Line 14
Invalid use of side-effecting or time-dependent operator in 'END CATCH' within a function.

Please assist.


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>