使用定义的文件大小创建 SQL 服务器数据库

Create SQL Server database with defined file size

我想创建一个 .mdf SQL 服务器数据库文件,定义的文件大小为 512 KB:

using System.Data.SqlClient;

SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;Database=master");

if (connection.State == ConnectionState.Closed) 
     connection.Open();

var command = connection.CreateCommand();
command.CommandText = "CREATE DATABASE thedb ON PRIMARY (NAME='thedb', FILENAME='r:\thedb.mdf', SIZE = 512KB, " + 
     "MAXSIZE = UNLIMITED, FILEGROWTH = 500KB) LOG ON (NAME ='thedb_log', FILENAME = 'r:\thedb_log.ldf', SIZE = 512KB)";

command.ExecuteNonQuery();

这将创建一个大小为 8 MB 的 .mdf 文件和一个大小为 64.5 MB (!) 的 .ldf 文件...

如果我省略 LOG ON,那么 .ldf 文件的大小也是 8 MB。

来自MSDN reference

When size is not supplied for the primary file, the Database Engine uses the size of the primary file in the model database. The default size of model is 8 MB (beginning with SQL Server 2016 (13.x)) or 1 MB (for earlier versions). When a secondary data file or log file is specified, but size is not specified for the file, the Database Engine makes the file 8 MB (beginning with SQL Server 2016 (13.x)) or 1 MB (for earlier versions). The size specified for the primary file must be at least as large as the primary file of the model database.

检查模型数据库 mdf 文件的大小。您的新数据库不能小于该值。如果初始文件大小的数字太小,看起来默认为 8MB。您也许能够减小模型数据库的大小以获得小于 8MB 的数据库。

您创建的文件可能太小,SQL 服务器无法正常运行。如果您正在寻找小型单文件数据库,您可以查看 SQLLite.

为新数据库执行 create database that new database is created based on the model database. See The model Database and Creating New Databases. When defining a size 时,如果该大小小于模型数据库,则会忽略该大小:

The size specified for the primary file must be at least as large as the primary file of the model database.

由于模型数据库是 8MB,任何新数据库的默认(和最小)大小也是 8MB。

要使文件大小更小 DBCC SHRINKFILE 可以在模型数据库上执行。允许的最小大小为 3MB。

use model;
dbcc shrinkfile(modeldev, 3)

来自:https://github.com/SimonCropp/LocalDb#template-database-size