views:

37

answers:

3

I hava a stored procedure named PROC_fetchTableInfo (simple select from sys.tables) in a database named

Cust

I would like use this procedure in a another database named

Dept

I tried to execute this sp in this database using command

EXECUTE Cust.dbo.PROC_fetchTableInfo

but as a result I get tables from the database Cust. How to get this procedure to work in database Dept?

+2  A: 

Your procedure, Cust.dbo.PROC_fetchTableInfo looks at data in the Cust database. Sounds like you need a copy of it in the Dept database.

Alternately (and quite unsatisfactory to me) you can add a parameter that controls which database to query by building the query in the sproc dynamically.

Perhaps you could create it in some "Common" database and call it like EXEC Common..PROC_fetchTableInfo @databaseName='Dept'

Brad
+1, there isn't much more you can do (duplicate it or pass in parameter)
KM
Thanks for this!
jjoras
+2  A: 

A stored procedure is tighly bound to the objects in its code. If Cust.dbo.PROC_fetchTable references a table T, that is stricly the table T in schema dbo in database Cust. You can invoke the procedure from any other place, it will always refer to this table.

If you need to run the same procedure in another table on another database then the best solution, by far, is to have a new procedure: Dept.dbo.PROC_fetxTableInfo. This is better than the alternative of using Dynamic-SQL. While this seems counteruintuitive from a DRY and code reuse perspective, T-SQL is a data access language is not a programming language, leave your C/C# mind set at the door when you enter the database. Just have another procedure in the Dept database.

Remus Rusanu
+1, `leave your C/C# mind set at the door when you enter the database`
KM
Is there a place here for e.g Red Gate Multi Script? I mean that maybe I can use this tool to execute this procedure on different databases?
jjoras
Generating and maintaining the procedure from script generation tools, and automating the deployment of new versions on all databases of interest, is a valid practice.
Remus Rusanu
+2  A: 

This is possible (if you are trying to write some utility function that you can use across all databases). You can create it in the master database, give it a sp_ prefix and mark it as a system object.

use master

go

CREATE PROCEDURE dbo.sp_sys_tables_select
AS
SELECT * FROM sys.tables 

GO

EXEC sys.sp_MS_marksystemobject 'dbo.sp_sys_tables_select'
GO


EXEC tempdb.dbo.sp_sys_tables_select

EXEC msdb.dbo.sp_sys_tables_select
Martin Smith
+1 because is a good trick to know. Of course, using unsupported always runs the risks associated with unsupported features ;)
Remus Rusanu
Thanks, this really is a good trick to know!
jjoras