我需要使用PowerShell脚本将SQL azure数据库设置为只读。 我们怎么做呢?
答案 0 :(得分:2)
我创建了以下PS脚本,使数据库只读一段时间。这对寻求此类解决方案的任何人都有帮助。
Add-AzureAccount
$subscription = "subscriptioname";
$serverName = "servername";
$database = "dbname";
$userid = "user@servername";
$password = "password";
$sleeptimeinsecond = 120;
Select-AzureSubscription $subscription
# Create DB connection
$connectionString = "Server=tcp:$serverName.database.windows.net;
Database=master;User ID=$userid;
Password=$password;Trusted_Connection=False;MultipleActiveResultSets=True;Encrypt=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$connection.Open()
echo '**connection opened'
# Run readonly command on database
$command = New-Object System.Data.SQLClient.SQLCommand
$command.Connection = $connection
$command.CommandText = "ALTER DATABASE $database SET READ_ONLY"
$reader = $Command.ExecuteReader()
echo '**command executed'
echo "**Database is now in readonly state"
$reader.Close()
$connection.Close()
echo '**reader & connection object closed'
#sleep for some time till process is going on.
echo "**Sleeping for $sleeptimeinsecond seconds..."
Start-Sleep $sleeptimeinsecond
echo '**Awake from sleep'
#reopen connection
$connection.Open()
# Run read_write command on database
$command = New-Object System.Data.SQLClient.SQLCommand
$command.Connection = $connection
$command.CommandText = "ALTER DATABASE $database SET READ_WRITE"
$reader = $Command.ExecuteReader()
echo '**command executed'
echo "**Database is now in read_write state"
$reader.Close()
$connection.Close()
echo '**reader & connection object closed'
echo '**Script execution done'
答案 1 :(得分:1)
使用TSQL命令alter database,如此,
ALTER DATABASE [Foo] SET READ_ONLY WITH NO_WAIT
您可以通过以下几种方式执行该语句:sqlcmd
,Sql Server的Powershell提供程序和.Net的System.Data.SqlClient类。