Is it possible to create a global stored procedure at Sql server level - sql

I created a query that takes a database backup at certain specified location.
I want to use it as a stored procedure but this should act as a global stored procedure so that whenever this SP is called. Then database backup is taken.
It uses DB_Name() to take database backup of owner database.
Is it possible to create any such SP or Function.
I am using sql server 2005

first solution:
If you create your sp in the master database and mark it as a system object and prefix it with 'sp_' then a single copy will exist that will be shared by all databases.
and second solution from msdn:
Private and global temporary stored procedures, analogous to temporary tables, can be created with the # and ## prefixes added to the procedure name. # denotes a local temporary stored procedure; ## denotes a global temporary stored procedure. These procedures do not exist after SQL Server is shut down.
an example :
USE master
CREATE TABLE test (c1 VARCHAR(50))
INSERT test VALUES('master')
go
CREATE PROC sp_test AS
SELECT * FROM test
GO
USE northwind
CREATE TABLE test (c1 VARCHAR(50))
INSERT test VALUES('northwind')
USE pubs
CREATE TABLE test(c1 VARCHAR(50))
INSERT test VALUES('pubs')
USE pubs
EXEC sp_test --returns 'master'
USE master
EXEC sp_MS_marksystemobject sp_test
USE pubs
EXEC sp_test --returns 'pubs'
USE northwind
EXEC sp_test --returns 'northwind'

Three steps must be followed to create a "system" stored procedure that is accessible to all databases on the Server, as well as be able to run under the context of the current database when it is called.
Master Database - The stored procedure should be created in the Master database
Prefix Stored Procedure - The stored procedure name should be prefixed with sp_
Mark SP as System Object - Call sp_ms_marksystemobject to mark custom SP as a system object
Example Code Below
--Step 1, Create in master database
USE master
GO
--Step 2, Prefix with sp_ the custom proc
CREATE PROCEDURE sp_myCustomSystemProc
AS
BEGIN
PRINT 'myCustomCode'
END
GO
--Step 3, Mark as system object so proc executes in context of current db
EXEC sp_ms_marksystemobject 'sp_myCustomSystemProc'
GO

There are 3 requirement for such stored procedure
The stored procedure must be created in the master database.
The name of the stored procedure must start with “sp_“.
The stored procedure must be marked as a system object.
-- 1. Create the procedure in the master database
USE master
GO
-- 2. Create the procedure with the prefix sp_
CREATE PROCEDURE sp_[Stored_Procedure_Name]
AS
BEGIN
-- Insert the logic of your stored procedure here
END
GO
-- 3. Mark the stored procedure as a system object
EXEC sys.sp_MS_marksystemobject sp_[Stored_Procedure_Name]

Related

Is there any way to a script inside stored procedure in SQL Server?

I know it's a weird scenario. But I need to execute a script inside a stored procedure in SQL Server.
I've created a SQL script to create a test table and populate it with some of the data from the original table. This script is in a separate file.
I also updated some stored procedures to use test mode. I created a parameter called #IsTestMode in the stored procedures.
If #IsTestMode is true, it checks whether the test table exists or not. If the test table does not exist, It should run that SQL script to create the test table and populate it with the data from the original table.
Is it possible to execute SQL script (in a separate file) inside a stored procedure?
Instead of storing the script in a file, create a new stored procedure using that code, say dbo.CreateTestData. Then, in your main proc:
CREATE PROC dbo.Whatever
#IsTestMode BIT = 0 /*Default to no*/
AS
BEGIN
IF #IsTestMode = 1
EXEC dbo.CreateTestData;
DoOtherStuff...
END
GO

Can I have the same stored procedure with two different name?

Bellow, I have a stored procedure named usp_customer
CREATE PROCEDURE usp_customer
AS
BEGIN
SELECT * FROM CUSTOMER
END
I want to give the same exact stored procedure a second name usp_cust1
Note: I am not looking to rename or to create a new stored procedure, I want both names to work
In the end, I could use either EXEC usp_customer or EXEC usp_cust1
Thanks
edit: changed sp_ to usp_
One stored procedure can call another:
CREATE PROCEDURE usp_cust1
AS
BEGIN
EXEC usp_customer;
END;
Note that in SQL Server, you should not use the "sp_" prefix for stored procedures. That is best reserved only for system stored procedures.

Update Stored procedure (T-SQL ) modification automatically?

I have two identical stored procedures with dynamic query.
Let's say
Stored procedure A
Stored procedure B
Both are in different databases. But they have the same code (Not Complete Identical.4-5 lines differ).
Is there a way to update any modification done in stored procedure A to stored procedure B automatically?
Otherwise I always need to copy and paste changes manually. It is an error-prone activity. Can anyone help me on this ?
You could do something like that:
In database A:
design your stored procedure in a way, that you have a parameter for
the database in which you want to do the work
In database B:
Create a synonym for the procedure in database A
Example:
--create procedure in database A
create procedure dbo.StoredProc
(
#dbname --or dbid if you want
)
as
begin
--create your sql command here, using dynamic sql maybe
declare #sqlcmd NVARCHAR(MAX)=N''
set #sqlcmd = 'SELECT * FROM ' + #dbname + '.dbo.AnyTable'
exec sp_executesql #sqlcmd
end
--create a synonym for this procedure in database b:
create synonym dbo.StoredProc FOR databaseA.dbo.StoredProc
--then you can call your procedure in Database A and B like this:
declare #dbname NVARCHAR(100) = DB_NAME()
exec dbo.StoredProc #dbname
so you have to maintain your code only once, and in database b you only have kind of a "link" to this procedure.
hope this helps :)
This is basically what SSDT was designed for, the idea is that you write your T-SQL and schema as CREATE statements, you build a "dacpac" and then you use sqlpackage.exe to deploy the dacpac to whatever database you want.
Doing it this way you have an overhead of the SSDT project but it fixes exactly your main problem with the existing method "It is an error-prone activity."
My blog post shows how to get an existing database into SSDT (in this case adventureworks but replace adventureworks with your database):
https://the.agilesql.club/Blog/Ed-Elliott/AdventureWorksCI-Step2-MDF-To-Dot-Sql
Ed

Create Start Up SP that any time sql run, retrieval data base

I want Create Start Up Stored Procedure that, any time sql run
retrieval Data Base. this is my code , Where i was wrong? Please help me.
USE MASTER
GO
CREATE PROC SP_RetrievalDataBase
AS
BEGIN
EXEC sp_detach_db 'AdventureWorks2012'
CREATE DATABASE MyAdventureWorks
ON
(FILENAME = 'G:\SQL Server 2012\AdventureWorks2012_Database\AdventureWorks2012_Data.mdf'),
(FILENAME = 'G:\SQL Server 2012\AdventureWorks2012_Database\AdventureWorks2012_Log.ldf')
FOR ATTACH;
END
GO
EXEC sp_procoption 'SP_ReplaceDataBase', 'startup', '1'
try setting your last parameter to 'ON' something like
EXECUTE sp_procoption 'SP_ReplaceDataBase', 'startup', 'on';
and use 'off' when you want the automatic execution, something like this
EXECUTE sp_procoption 'SP_ReplaceDataBase', 'startup', 'off';
Warning
Please do not use sp_ prefix for your procedure names, as Microsoft strongly recommends not using this prefix for you procedure names. the reason for this is as follows by Microsoft
In SQL Server, the sp_ prefix designates system stored procedures. If
you use that prefix for your stored procedures, the name of your
procedure might conflict with the name of a system stored procedure
that will be created in the future. If such a conflict occurs, your
application might break if your application refers to the procedure
without qualifying the reference by schema. In this situation, the
name will bind to the system procedure instead of to your procedure.

Declaring stored procedures header and body separately

I'm writing stored procedures in SQL Server 2008. I need to create two procedures which will use each other.
Procedure A executes B and B executes A.
So I suppose I have to declare headers of procedures firstly. I've searched over internet but I can't find the answer how can I make it.
So, my question is: how can I declare header and body of stored procedure separately in SQL Server 2008?
You can't separate them but you can create a SP that calls another SP that not yet exist.
When you run this
create procedure TheFirst as
begin
exec TheSecond
end
and SP TheSecond does not exist you will get a message:
The module 'TheFirst' depends on the missing object 'TheSecond'. The
module will still be created; however, it cannot run successfully
until the object exists.
Update:
To avoid the messages you can first create an empty proc and add the code later in the script.
create procedure ProcB as
go
create procedure ProcA as
begin
exec ProcB
end
go
alter procedure ProcB as
begin
exec ProcA
end