We came across this little nugget the other day. There is a vendor application that likes to create databases on the same drive and override the default file locations we have defined. Yeah, I know, hard to believe yet another vendor product can go out of their way to take a perfectly good server and screw it up somehow. Anyway, this was a wonderful learning opportunity for myself and our team.

From the BOL:

Generally, attaching a database places it in the same state that it was in when it was detached or copied. However, in SQL Server 2005 and later versions, attach-and-detach operations both disable cross-database ownership chaining for the database.

Oh. Well. Thanks, I guess. Not sure why you set this one property apart from all the others. I mean, what about TRUSTWORTHY? Oh…looks like you do that as well, huh?

You can see this for yourself, just cut and paste the following into SSMS and run against an instance of MS SQL that has the AdventureWorks database. You will probably need to redefine where the data and log files are for the AdventureWorks database in the part below that does the attach.

–set the chaining to be on
ALTER DATABASE AdventureWorks
SET DB_CHAINING ON
GO
ALTER DATABASE AdventureWorks
SET TRUSTWORTHY ON
GO
–examine the option, 1 means it is enabled
SELECT is_db_chaining_on, is_trustworthy_on
FROM sys.databases
WHERE name = ‘AdventureWorks’
GO
–detach the database
USE master
GO
EXEC master.dbo.sp_detach_db @dbname = N’AdventureWorks’
GO
–attach the database
USE [master] GO
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks_Data.mdf’ ),
( FILENAME = N’E:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\AdventureWorks_Log.ldf’ )
FOR ATTACH
GO
–examine the option, 0 means it is disabled
SELECT is_db_chaining_on, is_trustworthy_on
FROM sys.databases
WHERE name = ‘AdventureWorks’
GO

Now, go one step further and do a backup and restore. Turns out that these options get turned off as well when restoring, so this is not unique to a reattach.