Once my friend ask to me, It is possible to mark a stored procedure as system object allow to run in user database context?
I said yes we can do. We have to follow two step which is mention below.
Step 1- The stored procedure name must begin with "sp_":
Create a stored procedure in Maser database which name begin with sp_
CREATEPROCEDUREsp_NewObject
@tableNMvarchar(100)
AS
BEGIN
IFEXISTS(SELECT *
FROM sys.objects
WHERE name=@tableNM
)
BEGIN
SELECT'true'[Exist]
END
ELSE
BEGIN
SELECT'false'[Exist]
END
END
GO
Note: A stored procedure created with "sp_" prefix can be used in any user database without specifying database/schema. But, the procedure still run in the context of master database and not the user database. Let’s create a procedure to test this:
Step 2- The stored procedure must be marked as system object explicitly:
You can mark a stored procedure as system object using sys.sp_MS_marksystemobject system procedure.
Below code will mark the procedure as system object:
USE[master]
GO
EXECsys.sp_MS_marksystemobjectsp_NewObject
GO
You can verify if the object is marked as system object:
USE [master]
SELECT name,is_ms_shipped
FROM sys.objects
WHERE name='sp_NewObject'
result:
name is_ms_shipped
----------------------------------------------------
sp_NewObject 1
sp_NewObject is now marked as system object and can be run in user database context:
USE [Your database name]
GO
EXEC sp_NewObject'Tbl_Name'
GO