在 PHP 中使用 sqlsrv (MSSQL) 的动态预准备语句


Dynamic prepared statements with sqlsrv (MSSQL) in PHP

生成语句元素

我正在尝试以通用方式创建 MSSQL 准备语句。

基本上,我遍历字段,并将它们添加到准备好的 SQL 字符串和引用参数中(向下滚动以查看代码(。

这会导致(删除名称(:

准备好的查询: :

插入到表格中

([字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],[字段],值(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?(

sPrepStatement:

return array(&$aLine[0],&$aLine[1],&$aLine[2],&$aLine[3],&$aLine[4],&$aLine[5],&$aLine[6],&$aLine[7],&$aLine[8],&$aLine[9],&$aLine[10],&$aLine[11],&$aLine[12],&$aLine[13],&$aLine[14]); 

准备声明

我尝试了以下 4 种方法来使其与 sqlsrv_prepare 语句一起使用:

$oSQLStmnt = sqlsrv_prepare($dbhandle, $sPreppedSQL, eval($sPrepStatement));
$fReturnPrepVals = function(){ return eval($sPrepStatement); } ;
$oSQLStmnt = sqlsrv_prepare($dbhandle, $sPreppedSQL, $fReturnPrepVals);
$oSQLStmnt = sqlsrv_prepare($dbhandle, $sPreppedSQL,$aPrepValues);
$oSQLStmnt = call_user_func_array('sqlsrv_prepare',array($dbhandle,$sPreppedSQL, eval($sPrepStatement)));

这要么不起作用,要么在数据库中插入空白。

这是执行 SQL 的循环:

foreach ($aLines as $iLineNum => $sLine) {
            $aLine = explode('|', $sLine);
            print_r($aPrepValues);
            print_r(eval($sPrepStatement));
            sqlsrv_execute($oSQLStmnt);
        }

eval($sPrepStatement)工作得很好,这是有道理的。但我认为在 prepare 语句中工作"解析得太早"。它实际上应该只在执行查询时解析,但我不知道如何实现这一点。


用于生成 sql 语句的代码:

<?php
//Setup the basic query
        $sSql = "INSERT INTO " . $sQName . "'n";
        $sFieldNames = "(";
        $sValues = "VALUES(";
        //This will be evalled to prepare the query, so inserting will be easy.
        $sPrepStatement = "return array(";
        //FieldIndex to keep track of the current column number
        $iFI = 0;
        $aLine = array();
        foreach ($aSQLQueries[$sQName]['fields'] as $sFieldName => $sQ) {
            $sFieldNames .= "[" . $sFieldName . "],";
            $sValues .= "?,";
            //Init the $aLine var to prevent errors
            $aLine[$iFI] = '';
            //This will be evalled, so no "" as that would parse it directly
            //The values wil be passed by reference
            $sPrepStatement .= '&$aLine[' . $iFI . '],';
            //Different approach
            $aPrepValues[] = &$aLine[$iFI];
            $iFI++;
        }
        $sFieldNames = substr($sFieldNames, 0, -1) . ")";
        $sValues = substr($sValues, 0, -1) . ")";
        $sPrepStatement = substr($sPrepStatement, 0, -1) . ");";
        $sPreppedSQL = $sSql . $sFieldNames . " " . $sValues;

我最终让它与 PDO 一起工作,只是发现它无法一次处理数百万个导入,所以我最终使用了 CSV 导入