Php 如何使用T-SQL和语句对象进行后期绑定?

Php 如何使用T-SQL和语句对象进行后期绑定?,php,tsql,zend-framework2,zend-db,Php,Tsql,Zend Framework2,Zend Db,我正在寻找一个长期的解决方案,以适应需要使用后期绑定的T-SQL查询。MS-SQL的后期绑定语法是一个难题,也是独一无二的 当谈到T-SQL后期绑定时,我们需要声明和设置,比如 DECLARE @id int SET @id = 1 SELECT * FROM users WHERE user_id = @id; 现在Zend Framework 2构建了如下查询 $select = new Sql\Select(); $select->from(['users']); $select

我正在寻找一个长期的解决方案,以适应需要使用后期绑定的T-SQL查询。MS-SQL的后期绑定语法是一个难题,也是独一无二的

当谈到T-SQL后期绑定时,我们需要
声明
设置
,比如

DECLARE @id int 
SET @id = 1
SELECT * FROM users
WHERE user_id = @id;
现在Zend Framework 2构建了如下查询

$select = new Sql\Select();
$select->from(['users']);
$select->columns(['*']);
$select->where->equalTo('user_id', '@id');
// Create the statement object
$stmt = $sql->prepareStatementForSqlObject();
$stmt->prepare();
$stmt->execute(['@id' => 1]);
现在,在ZF2的语句对象的
prepare()
方法中,我可以将我的
DECLARE
SET
前缀添加到已经存在的
$sql
,如下所示:

 public function prepare($sql = null, array $options = [])
{
    if ($this->isPrepared) {
        throw new Exception\RuntimeException('Already prepared');
    }
    $sql = ($sql) ?: $this->sql;
    $options = ($options) ?: $this->prepareOptions;

    $pRef = &$this->parameterReferences;
    // change substr_count($sql, '?') <-> TO |-> substr_count($sql, '@')
    for ($position = 0, $count = substr_count($sql, '?'); $position < $count; $position++) {
        if (!isset($this->prepareParams[$position])) {
            $pRef[$position] = ['', SQLSRV_PARAM_IN, null, null];
        } else {
            $pRef[$position] = &$this->prepareParams[$position];
        }
    }

    // <!-- Beg of custom stuff. I can grab the $sql string, that we built up here, with $this->sql, and prefix it with the T-SQL required DECLARE and SET. -->
    // We can get @id and 1 through the execute()'s call and the parameter Container.
    $prependSQL = "DECLARE @id int";
    $prependSQL .= "SET @id = 1";
    $prependSQL .= $this->sql;
    $this->sql = $prependSQL;
    $sql = $this->sql;
    // <!-- End of custom stuff -->
    $this->resource = sqlsrv_prepare($this->sqlsrv, $sql, $pRef, $options);

    $this->isPrepared = true;

    return $this;
}
公共函数prepare($sql=null,数组$options=[]))
{
如果($this->isPrepared){
抛出新异常\RuntimeException('已准备就绪');
}
$sql=($sql)?:$this->sql;
$options=($options):$this->prepareOptions;
$pRef=&$this->parameterReferences;
//将substr_计数($sql,“?”)更改为|->substr_计数($sql,“@”)
对于($position=0,$count=substr_count($sql,“?”);$position<$count;$position++){
如果(!isset($this->prepareParams[$position])){
$pRef[$position]=['',SQLSRV_参数输入,null,null];
}否则{
$pRef[$position]=&$this->prepareParams[$position];
}
}
// 
//我们可以通过execute()的调用和参数容器获得@id和1。
$prependSQL=“DECLARE@id int”;
$prependSQL.=“SET@id=1”;
$prependSQL.=$this->sql;
$this->sql=$prependSQL;
$sql=$this->sql;
// 
$this->resource=sqlsrv\u prepare($this->sqlsrv,$sql,$pRef,$options);
$this->isPrepared=true;
退还$this;
}
我应该这样做吗?我觉得我在破坏ZF2的DB抽象层。任何方向或输入将是伟大的,我想如何做到这一点