Question

Looking through our procedures on MyDatabase, I found several that reference itself, e.g.

SELECT colA, colB FROM [MyDatabase].[Schema].[Table]

Is there any benefit to including the database name in this way? I can't see any particular reason to do this, and it makes the procs a little less portable.

Of course, you would need to include the db name if you were doing

SELECT colC, colD FROM [MyOtherDatabase].[Schema].[Table]

It's a fairly minor issue, but my first reaction is 'probably not best practice' so I was wondering if there's any benefit I'm missing or if we should remove the db name from all these references.

Was it helpful?

Solution

This is a bit long for a comment.

I would opt to remove the database name, but I don't know if this is a "best practice". When doing development, I sometimes have a tendency to keep multiple versions of the same database on a server. Specific database references in code would cause a problem. (A better development environment is to have another dedicated instance of SQL Server.)

However, you should think about:

  • Whether your application uses only one database or multiple databases. If there are multiple databases, you might want to move stored procedures from one to another, so the explicit references would be useful.
  • Any impact with your version control software.
  • Your process for maintaining the database code, adding in new functionality and fixing problems.

OTHER TIPS

Considering that, the owner is dbo; you can transform the line

SELECT colA, colB FROM [MyDatabase].[Schema].[Table]

By saying

use [MyDatabase] 
GO
SELECT colA, colB FROM [Table]

Generally in your procedure, all the queries will be referencing tables in same database but in case you have queries which has cross DB reference then you will have to go for 3 part name DB.Owner.Table

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top