Skip to content

Instantly share code, notes, and snippets.

@mikeblas
Last active September 3, 2024 07:34
Show Gist options
  • Save mikeblas/dd1a92e4f5a9202623acc4d594b8f64f to your computer and use it in GitHub Desktop.
Save mikeblas/dd1a92e4f5a9202623acc4d594b8f64f to your computer and use it in GitHub Desktop.
get `sp_attach_db` scripts for all databases
-- 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