If you are going to pass the error message to function, then try this:
CREATE FUNCTION Fun_GetErrorNumber
(
@command NVARCHAR(MAX)
)
RETURNS INT
AS
BEGIN
RETURN CAST(SUBSTRING(@q,PATINDEX('%[0-9]%',@q),PATINDEX('%,%',@q)-PATINDEX('%[0-9]%',@q)) AS INT)
END
But if you want to pass the query to function, you should take note that executing command inside Function is not valid and you need to use stored procedure instead. Like this:
CREATE PROCEDURE Pro_Execute
(
@command NVARCHAR(MAX) ,
@num INT OUTPUT
)
AS
BEGIN
BEGIN TRY
EXEC(@command);
SET @num = 0;
END TRY
BEGIN CATCH
SET @num = ERROR_NUMBER();
END CATCH;
END;
And call it like this:
DECLARE @res INT
EXEC Pro_Execute 'Select 1/0' ,@num = @res output
SELECT @res
The above SP
will get the command and execute it. If non-fatal error occurred while executing the command, error number will be returned.
Reading this article may help you decorate your solution in better way