@echo off
REM ie. --> attachdb dBname

cls

:attach
set /p dBname="Type in your database name > "
if [%dBname%] EQU [] goto noargs

if NOT exist c:\"program files\microsoft sql server\mssql\data"\%dBname%.mdf goto error
if NOT exist c:\"program files\microsoft sql server\mssql\data"\%dBname%.ldf goto error

if not exist c:\advantage mkdir c:\advantage

echo use master > c:\advantage\~attach.sql
echo go >> c:\advantage\~attach.sql
echo exec sp_attach_db @dbname = N'%dBname%', >> c:\advantage\~attach.sql
echo 	@filename1=N'c:\program files\microsoft sql server\mssql\data\%dBname%.mdf', >> c:\advantage\~attach.sql
echo 	@filename2=N'c:\program files\microsoft sql server\mssql\data\%dBname%.ldf' >> c:\advantage\~attach.sql
echo go >> c:\advantage\~attach.sql

osql -U sa -P advantagesystem -i c:\advantage\~attach.sql

del /Q c:\advantage\~attach.sql
exit

:noargs
if exist c:\advantage\~*.* del c:\advantage\~*.*
dir c:"\program files\microsoft sql server\mssql\data\*.mdf" /b /O:D > c:\advantage\~mdf.txt
for /F "tokens=1 delims=." %%i in (c:\advantage\~mdf.txt) do echo %%i >> c:\advantage\~mdf2.txt
for /F %%i in (c:\advantage\~mdf2.txt) do osql -U sa -P advantagesystem -Q "exec sp_attach_db @dbname = N'%%i', @filename1=N'c:\program files\microsoft sql server\mssql\data\%%i.mdf', @filename2=N'c:\program files\microsoft sql server\mssql\data\%%i.ldf'" > c:\advantage\logs\attach.txt

del /Q c:\advantage\~*.*
exit

:error
cls
echo %dBname% does not exist
echo.
goto attach