MSSQL database stuck in recovery state with PHP

I am trying to restore a database to another server via PHP. I managed to execute all the necessary commands, but the database constantly hangs in the "Restore ..." state on the server.

I searched for and followed the answer on SQL Server: Database got stuck in "Recover" state with PHP (which leads to in this article ), but that didn't work for me; I am getting an error when I try to change the environment to a recently restored database.

code:

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");

      

The returned error is:

[Microsoft][SQL Server Native Client 11.0][SQL Server]Database 'db_name' cannot be opened. It is in the middle of a restore.

      

Do you have any ideas on how I can solve this? The only authority on the workaround for the error described in my previously linked article seems to be the exact article that doesn't work as you can see.

Thank!

+3


source to share


1 answer


I don't have a 50 reputation yet, so feel free to move this to the comments section. I don't see your names in the database, including the brackets "[]". If you have database names with spaces or special characters, you need parentheses to correctly define the object. And as Mitch said, based on what you are doing, there is no reason for two restore operations; just add the RECOVERY option first and be done with it.



0


source







All Articles