Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create database with t-SQL without specifying its file name

I try to run the following SQL statement to create a database:

string strSQL = "CREATE DATABASE " + strDatabaseName +
    " ON PRIMARY " +
    "(" +
    "SIZE = 10MB, FILEGROWTH = 20%) " +
    "LOG ON (" +
    "SIZE = 5MB, " +
    "FILEGROWTH = 20%)" +
    " COLLATE SQL_Latin1_General_CP1_CI_AS;";

I want to use a default .mdf and .ldf file locations, but specify the size and file-growth parameters. The issue is that when I run it I get an error:

File option FILENAME is required in this CREATE/ALTER DATABASE statement.

So is there's any way to do what I'm trying to achieve?

like image 256
ahmd0 Avatar asked Oct 20 '22 22:10

ahmd0


1 Answers

Try This.

      string strSql = " DECLARE @data_path nvarchar(256); "+
"SET @data_path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(physical_name)) - 1)"+
 "                 FROM master.sys.master_files"+
  "                WHERE database_id = 1 AND file_id = 1);"+


"EXECUTE ('CREATE DATABASE " + strDataBaseName +
"ON PRIMARY "+
   "("+
   "  NAME = FileStreamDB_data "+
   " ,FILENAME = ''' + @data_path + '" + strDataBaseName +"_data.mdf''"+
   " ,SIZE = 10MB"+
   " ,MAXSIZE = 50MB"+
   " ,FILEGROWTH = 15%"+
   " )LOG ON ("+
   " NAME = FileStreamDB_log"+
   " ,FILENAME = ''' + @data_path + '" + strDataBaseName + "_log.ldf''" +
   " ,SIZE = 5MB, "+
   " FILEGROWTH = 20%)"+
"     COLLATE SQL_Latin1_General_CP1_CI_AS')";
like image 200
sahalMoidu Avatar answered Oct 27 '22 08:10

sahalMoidu