Here are the code snippets for programmatically creating .ldf files
Below are 3 methods.
Method -1
In my case, I have my database in the DATA folder.
You can get the full path to your database by right-clicking, and then going to the properties you can copy the full path to your database
As in my case, the path is as follows.
C: \ Program Files \ Microsoft SQL Server \ MSSQL11.DRIBBLEE \ MSSQL \ DATA
Now here is the first method using the storage procedure (sp_attach_single_file_db) and passing its arguments (database name and physical path)
USE [master] GO EXECUTE sp_attach_single_file_db @dbname='AdventureWorksDW_2012', @physname=N'C:\ProgramFiles\MicrosoftSQLServer\MSSQL11.DRIBBLEE\MSSQL\DATA\AdventureWorksDW2012_Data.mdf' GO
execute the code, which after executing the code, go to the database folder where it is located, you will see the .ldf file there.
However, you will receive the following message in your
The physical file name "C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2012_log.ldf" may be incorrect. New log file 'C:\Program Files\Microsoft SQL Server\MSSQL11.DRIBBLEE\MSSQL\DATA\AdventureWorksDW_2012_log.ldf' was created.
Now you can attach your database and after the Attach Database application, right-click on the name of your server in the Object Explorer and update it.
Method 2
If your database contains one or more log files, you can use the following
CREATE DATABASE db_namehere ON ( FILENAME=N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\db_namehere.mdf') FOR ATTACH_REBUILD_LOG GO
Method 3
If the database has only one log file, you can use this
CREATE DATABASE db_name ON ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TestDb.mdf') FOR ATTACH GO
Further you can read in BOOKs Online for more information.