Last active
September 3, 2024 07:34
-
-
Save mikeblas/dd1a92e4f5a9202623acc4d594b8f64f to your computer and use it in GitHub Desktop.
get `sp_attach_db` scripts for all databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- due to https://www.mssqltips.com/sqlservertip/1786/auto-generate-sql-server-database-attach-and-detach-scripts/ | |
-- modified to use NVARCHAR for names | |
SET NOCOUNT ON | |
DECLARE @cmd NVARCHAR(MAX), | |
@dbname NVARCHAR(200), | |
@prevdbname NVARCHAR(200) | |
SELECT @cmd = N'', @dbname = N';', @prevdbname = N'' | |
CREATE TABLE #Attach | |
(Seq INT IDENTITY(1,1) PRIMARY KEY, | |
dbname SYSNAME NULL, | |
fileid INT NULL, | |
filename NVARCHAR(1000) NULL, | |
TxtAttach NVARCHAR(MAX) NULL | |
) | |
-- find files names that begin with "F" | |
INSERT INTO #Attach | |
SELECT DISTINCT DB_NAME(dbid) AS dbname, fileid, filename, CONVERT(NVARCHAR(MAX),'') AS TxtAttach | |
FROM master.dbo.sysaltfiles | |
WHERE dbid IN (SELECT dbid FROM master.dbo.sysaltfiles | |
WHERE SUBSTRING(filename,1,1) IN ('F')) | |
AND DATABASEPROPERTYEX( DB_NAME(dbid) , 'Status' ) = 'ONLINE' | |
AND DB_NAME(dbid) NOT IN ('master','tempdb','msdb','model') | |
ORDER BY dbname, fileid, filename | |
UPDATE #Attach | |
SET @cmd = TxtAttach = | |
CASE WHEN dbname <> @prevdbname | |
THEN CONVERT(NVARCHAR(200), N'exec sp_attach_db @dbname = N''' + dbname + N'''') | |
ELSE @cmd | |
END + N',@filename' + CONVERT(NVARCHAR(10),fileid) + '=N''' + filename + N'''', | |
@prevdbname = CASE WHEN dbname <> @prevdbname THEN dbname ELSE @prevdbname END, | |
@dbname = dbname | |
FROM #Attach | |
SELECT TxtAttach | |
FROM | |
(SELECT dbname, MAX(TxtAttach) AS TxtAttach FROM #Attach | |
GROUP BY dbname) AS x | |
DROP TABLE #Attach | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment