存储过程虽然仅影响第一行

时间:2014-01-28 08:51:31

标签: php sql-server stored-procedures while-loop

我尝试使用php和存储过程插入一些数据。存储过程工作正常但仅适用于第一行。

PHP:

$sql = "SELECT * FROM [importliste_TCSv3]";

$stmt = sqlsrv_query($conn, $sql);

if ($stmt === false ) {
    die (print_r(sqlsrv_errors(), true));
}

while ($row = sqlsrv_fetch_array($stmt)) {
    // print works fine without call proc
    $query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
    $params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);

    $stmt = sqlsrv_query($conn, $query, $params);

    if ($stmt === false) {
        die (print_r(sqlsrv_errors(), true));
    }
}

存储过程:

ALTER proc [dbo].[difInport]
@mandant_id varchar(50),
@kostenstelle varchar(50),
@vorname varchar(50),
@nachname varchar(50),

@ci_nummer int,
@anzahl_monitore_old int,
@raum varchar(50),
@gebäude varchar(50),
@bemerkung text,

@hardware_typ varchar(50),
@anzahl_monitore_new varchar(50),
@zubehör text

as

BEGIN
    SET NOCOUNT ON;

    DECLARE
    @latestPersonID int,
    @latestCmoID int,
    @latestFmoID int

    INSERT INTO [RC.Persons] (kostenstelle, vorname, nachname) VALUES (@kostenstelle, @vorname, @nachname);
    SET @latestPersonID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.CMO] (ci_nummer, anzahl_monitore, raum, gebäude, bemerkung) values (@ci_nummer, @anzahl_monitore_old, @raum, @gebäude, @bemerkung);
    SET @latestCmoID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.FMO] (hardware_typ, anzahl_monitore, zubehör) values (@hardware_typ, @anzahl_monitore_new, @zubehör);
    SET @latestFmoID = (SELECT SCOPE_IDENTITY())

    INSERT INTO [RC.Persons_RC.CMO] (cmo_id, person_id) VALUES (@latestCmoID, @latestPersonID);

    INSERT INTO [RC.Persons_RC.FMO] (fmo_id, person_id) VALUES (@latestFmoID, @latestPersonID);

    INSERT INTO [RC.Persons_RC.Mandant] (person_id, mandant_id) VALUES (@latestPersonID, @mandant_id);

END

我读到了这个问题:Call mysql PROCEDURE inside while loop works only first time 但是我没有给出任何结果集,或者是选择结果问题的set声明?

1 个答案:

答案 0 :(得分:1)

您正在覆盖$stmt变量。更改在while循环中使用的变量的名称:

while ($row = sqlsrv_fetch_array($stmt)) {
    // print works fine without call proc
    $query = "{call difInport(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)}";
    $params = array("0gtp", $row["Kostenstelle"], $row["Vorname"], $row["Nachname"], $row["CI-Nummer"], $row["cmo_mon"], $row["Raum"], $row["Gebaeude"], $row["Bemerkung"], $row["Hardware"], $row["fmo_mon"], $row["Zubehoer"]);

    $stmt_proc = sqlsrv_query($conn, $query, $params);

    if ($stmt_proc === false) {
        die (print_r(sqlsrv_errors(), true));
    }
}