使用 t-SQL 创建数据库,而不指定其文件名
本文关键字:文件名 t-SQL 创建 数据库 使用 | 更新日期: 2023-09-27 18:36:25
我尝试运行以下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 文件位置,但指定大小和文件增长参数。问题是当我运行它时出现错误:
文件选项文件名在此创建/更改数据库中是必需的 陈述。
那么有什么方法可以做到我想要实现的目标吗?
试试这个。
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')";
根据@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%
);