我正在尝试通过PHP将数据库还原到其他服务器。我设法执行所有需要的命令,但数据库一直挂在服务器上的“恢复...”状态。
我已经搜索并按照SQL Server: Database stuck in “Restoring” state with PHP上的答案(导致this article),但这对我不起作用;尝试将环境更改为新恢复的数据库时出错。
代码:
sqlsrv_configure( "WarningsReturnAsErrors", 0 );
$connOptions = ["Database"=>"master"];
$sqlConnection = sqlsrv_connect("server_name\\SERVER", $connOptions);
sqlsrv_query($sqlConnection, "USE master");
$sql = "IF EXISTS(SELECT name FROM sys.databases
WHERE name = 'db_name')
DROP DATABASE db_name";
sqlsrv_query($sqlConnection, $sql);
$sql = "RESTORE FILELISTONLY FROM DISK='$path'";
$logicalNamesStatement = sqlsrv_query($sqlConnection, $sql);
$moveArray = [];
while($logicalNames = sqlsrv_fetch_array($logicalNamesStatement, SQLSRV_FETCH_ASSOC)){
if($logicalNames['Type'] === "D"){
$moveArray['MDF'] = $logicalNames['LogicalName'];
}
elseif($logicalNames['Type'] === "L"){
$moveArray['LDF'] = $logicalNames['LogicalName'];
}
}
$localDbPath = "c:\\Program Files\\Microsoft SQL Server\\MSSQL11.SERVER\\MSSQL\\DATA\\";
$sql = "RESTORE DATABASE db_name FROM DISK='$path'
WITH
MOVE '" . $moveArray['MDF'] . "' TO '" . $localDbPath . "db_name.mdf',
MOVE '" . $moveArray['LDF'] . "' TO '" . $localDbPath . "db_name_log.ldf',
REPLACE,
STATS=10";
sqlsrv_query($sqlConnection, $sql);
$sql = "RESTORE DATABASE db_name FROM DISK='$path' WITH REPLACE, RECOVERY";
sqlsrv_query($sqlConnection, $sql);
sqlsrv_query($sqlConnection, "USE db_name");
返回的错误是:
[Microsoft][SQL Server Native Client 11.0][SQL Server]Database 'db_name' cannot be opened. It is in the middle of a restore.
您对我如何解决这个问题有什么想法吗?我之前链接的文章中描述的错误的解决方法的唯一权限似乎是那篇确切的文章,它无法正常工作。
谢谢!
答案 0 :(得分:0)
我还没有50个声望,所以请随意将其移至评论部分。我没有看到您的数据库名称,包括括号" []"。如果您有任何带空格或特殊字符的数据库名称,则需要使用括号来正确识别对象。正如Mitch已经说过的那样,基于你正在做的事情,没有理由进行两次恢复操作;只需将RECOVERY选项添加到第一个选项中即可完成。