Creating a database programmatically in SQL Server

后端 未结 6 2285
情书的邮戳
情书的邮戳 2020-11-30 09:20

How can I create a database programmatically and what is the minimum information I need to do this?

Please no \"SQL Server Management Object API \"

6条回答
  •  难免孤独
    2020-11-30 09:52

    You need connection information: server, possibly instance, a user having create database rights on that server/instance and the corresponding password. Then you can use SMO for creating the database. Here is a small PowerShell example that you can very easily "translate" to C#, for example:

    [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | Out-Null
    
    $s = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerInstance)
    
    # Instantiate the database object and add the filegroups
    $db = New-Object Microsoft.SqlServer.Management.Smo.Database($s, $DatabaseName)
    $primaryFG = New-Object Microsoft.SqlServer.Management.Smo.FileGroup($db, 'PRIMARY')
    $db.FileGroups.Add($primaryFG)
    
    # Create Data file
    $syslogname = $DatabaseName + '_SysData'
    $dbdsysfile = New-Object Microsoft.SqlServer.Management.Smo.DataFile($primaryFG, $syslogname)
    $primaryFG.Files.Add($dbdsysfile)
    $dbdsysfile.FileName = $s.MasterDBPath + '\' + $syslogname + '.mdf'
    $dbdsysfile.Size = [double](5.0 * 1024.0)
    $dbdsysfile.GrowthType = 'KB'
    $dbdsysfile.Growth = 10000.0
    $dbdsysfile.IsPrimaryFile = 'True'
    
    # Create Log file
    $loglogname = $DatabaseName + '_Log'
    $dblfile = New-Object Microsoft.SqlServer.Management.Smo.LogFile($db, $loglogname)
    $db.LogFiles.Add($dblfile)
    $dblfile.FileName = $s.MasterDBLogPath + '\' + $loglogname + '.ldf'
    $dblfile.Size = [double](10.0 * 1024.0)
    $dblfile.GrowthType = 'KB'
    $dblfile.Growth = 10000.0
    
    # Create database with READ_COMMITTED_SNAPSHOT isolation level.
    # Other options can be set on $db object before calling Create.
    $db.IsReadCommittedSnapshotOn = $true
    
    $db.RecoveryModel = [Microsoft.SqlServer.Management.Smo.RecoveryModel]::Simple
    $db.Create()
    

提交回复
热议问题