I'm trying to write a UDF to translate a string that is either a guid or a project code associated with that guid into the guid:
CREATE FUNCTION fn_user_GetProjectID
(
@Project nvarchar(50)
)
RETURNS uniqueidentifier
AS
BEGIN
declare @ProjectID uniqueidentifier
BEGIN TRY
set @ProjectID = cast(@Project as uniqueidentifier)
END TRY
BEGIN CATCH
set @ProjectID = null
END CATCH
if(@ProjectID is null)
BEGIN
select @ProjectID = ProjectID from Project where projectcode = @Project
END
return @ProjectID
END
This works fine if the above code is embedded in my Stored Procedures, but I'd like to make a function out of it so that I follow DRY.
When I try to create the Function, I get errors like this:
Msg 443, Level 16, State 14, Procedure fn_user_GetProjectID, Line 16
Invalid use of side-effecting or time-dependent operator in 'BEGIN TRY' within a function.
Does anyone have an idea how I can get around this error?
Edit: I know I can't use Try-Catch in a Function, I guess a simplified questions would be, is there a way to do a cast that will just return NULL if the cast fails, instead of an error?