使用sqlsrv切换数据库的正确方法是什么?

时间:2016-10-01 15:03:29

标签: php sql sql-server database sql-server-2008

我现在开始使用带有mssql的PHP 7,我需要将sql函数从mssql_切换到sqlsrv_。当我使用mssql函数时,我正在使用函数mssql_change_db更改数据库,但正如我现在看到的,没有替代函数可以使用而不是使用此函数。我想通过在每个查询中使用USE [DB]来使这个功能自己购买,但它似乎没用或无效。我想过另一种方式,这似乎更好。
我想到的另一种方法是在每个表名之前添加DB_NAME.dbo.table。
我也开始以这种方式构建一个函数,它找到表名并在表名之前自动添加带有“.dbo”的数据库名称。
以下是我到目前为止所做的事情:(我刚刚开始构建它)
这只是一个例子,诅咒尚未完成。

public function exec($mainQuery, $db = NULL)
{
    if(isset($db)) {
        $query = $mainQuery;
        $query = explode('from ', $query); 
        $query = $query[1]; // Getting the rest of the query after the word "Form"
        if (strpos($query, 'where') !== false) { // Checking if the rest of the query includes the word "Where"
            $query = explode('where', $query); // Taking the word before the word "Where"
            $tableName = $query[0];
        }
        else { // The rest of the query is actually the table name, because there is no "Where" in the query
            $tableName = $query;
        }

        $pQuery = str_replace( "$tableName", " $db.dbo.$tableName", $mainQuery); // Replacing the table name with the DB.dbo.tablename

        return sqlsrv_query($this -> sqlHandle, $pQuery);
    }
    else {
        return sqlsrv_query($this -> sqlHandle, $mainQuery);
    }
}


我也应该为JOIN,INSERT(INTO),UPDATE构建它。
我不知道为什么,但我觉得这样做很糟糕,
这就是为什么我问你切换数据库的更好方法是什么。
提前致谢。

1 个答案:

答案 0 :(得分:1)

使用USE Database或者从PHP运行的查询中更改数据库是一个不太好的主意(你用DB名称做了一个非常好的技巧)。对于那种东西,最好使用存储过程并从PHP调用它们。

在这种情况下,你不需要考虑你的表是什么模式或数据库,所有都是用SP编写的。

另一种方法是为所有用户使用一个默认数据库,并在需要从非默认数据库获取表时使用USE database

相关问题