使用t-SQL创建数据库而不指定其文件名

时间:2013-10-22 23:26:13

标签: c# asp.net sql sql-server tsql

我尝试运行以下SQL语句来创建数据库:

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

我想使用默认的.mdf和.ldf文件位置,但是指定大小和文件增长参数。问题是当我运行它时出现错误:

  

此CREATE / ALTER DATABASE中需要文件选项FILENAME   言。

那么有什么方法可以做我想要实现的目标吗?

2 个答案:

答案 0 :(得分:4)

试试这个。

      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')";

答案 1 :(得分:-1)

根据@ sahalMoidu的建议,这里是他的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%
);