Sql-server – User Defined Function (UDF) in master database

functionssql serversql-server-2008-r2

I have a function which is used in more than a dozen databases. I want this function to be accessible in all the databases by writing it only once, so I want to write the function in master database so that my function can be accessed easily.

Is there any problem in writing the user defined function in master db?

When surfing the Internet some suggested converting the function to a system function. (Using “EXEC sp_ms_marksystemobject 'fn_db_name' ”).

Is there a necessity to convert the function created in master db to system function? If yes why?

Best Answer

I agree with Jonathan - as long as the function isn't supposed to return local data based on the calling database context, put the function in a utility database (this is also where I put things like numbers and calendar tables, splitting functions, etc):

USE UtilityDB;
GO
CREATE FUNCTION dbo.whatever() RETURNS ...
GO

Now, in every database that needs to access the function, just create a synonym:

CREATE SYNONYM dbo.whatever() FOR UtilityDB.dbo.whatever();

This way each database can still reference the function using a simple, 2-part name - and they don't have to know or care where it actually exists. And you only have to maintain a single copy of the function.

(And in fact, you can put the synonym in the model database, so that it is created in new databases automatically.)

The reason I dislike putting user objects in master - unless they really do need to be globally available and contextual to the calling database, like your own customized version of sp_spaceused or sp_helpindex - is that people aren't looking for user objects in master, and they're less discoverable there. They also make it harder to migrate your user databases elsewhere, because you need to remember the user stuff you put in master, too. If you are absolutely dead-set against creating or using a utility database for this, I think msdb is a more practical choice for a central location.