5

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?

2 Answers 2

4

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')";
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. That worked nicely. I see that you took the path to the 1st available database and used it to construct my new DB path. I'm curious, is DB with id=1 always master.mdf? And will this work on a remote SQL Server?
Yes.It should be, since there wont be a sql-server instance without a master db and the sql server creates the master database first so the db should have id =1
Note you can get the actual default paths from the server properties SERVERPROPERTY('instancedefaultdatapath') and SERVERPROPERTY('instancedefaultlogpath'). This is what SSMS is doing under the hood - check out SQL Server Profiler when you open the New Database dialog.
-1

Based on @sahalMoidu's suggestions, here's a slightly updated version of his SQL:

DECLARE @dbFileName nvarchar(256);
CREATE DATABASE [testdb2] COLLATE SQL_Latin1_General_CP1_CI_AS;
SET @dbFileName = (SELECT [name] FROM master.sys.master_files WHERE [database_id] = DB_ID(N'testdb2') AND file_id = 1);
EXECUTE ('ALTER DATABASE [testdb2]
 MODIFY FILE(
NAME = ''' + @dbFileName + ''',
SIZE = 5MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 20%
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.