簡體   English   中英

如何將相同的標識列添加到不同的表?

[英]How to add same identity column to different tables?

我的 MSSQL 中有以下存儲過程。

declare @UserNum as int

    insert into auth_table( ID, Password, Login, AuthType, IdentityNo ) 
    values(@id, pwdencrypt(@password), '0', 1, '7700000000000' )

    set @UserNum = @@identity


    insert into charge_auth(usernum, type, expiredate, payminutes)
    values(@UserNum, 0, DATEADD(day, 1000, getdate()), 0)
    
    insert into CashDB..cashaccount (id,UserNum,Cash,CashBonus,UpdateDateTime) values(@id,@UserNum,0,0,GETDATE())

    select @UserNum as usernum

我希望能夠將其轉換為 PDO PHP,我設法完成了第一次插入。 問題是有一個UserNum值在所有表中都是持久的。 當我將數據插入第一個表時,會生成這個UserNum ,它是一個自動遞增的值。 我想同時把這個傳遞給其他表,所以它們通過這個值連接起來。

我不知道如何使用 PHP 和 PDO 來做到這一點。

提前致謝。

試試這個。 有關分步說明,請參閱評論。 (未經測試!)

// Construct query, using positional variables (?).
$sql =
    'INSERT INTO ' .
    '`auth_table` ' .
    '( `ID`, `Password`, `Login`, `AuthType`, `IdentityNo` )  ' .
    'VALUES ' .
    '(?, pwdencrypt(?), ?, ?, ?)';
// Create prepared statement from query.
$statement = $pdo->prepare($sql);
// Bind parameters by position, the index of which is 1-based.
$bindIndex = 1;
// Increase index on every line. Enforce type as we go.
$statement->bindValue($bindIndex++, $id, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, $plaintextPassword, PDO::PARAM_STR);
$statement->bindValue($bindIndex++, '0', PDO::PARAM_STR);
$statement->bindValue($bindIndex++, 1, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, '7700000000000', PDO::PARAM_STR);
$statement->execute();

// This is your @@identity
$userNum = $pdo->lastInsertId();

// Second insert.
$sql =
    'INSERT INTO ' .
    '`charge_auth` ' .
    '(`usernum`, `type`, `expiredate`, `payminutes`) ' .
    'VALUES ' .
    '(?, ?, DATEADD(day, ?, getdate()), ?)';
$statement = $pdo->prepare($sql);
$bindIndex = 1;
$statement->bindValue($bindIndex++, $userNum, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, 0, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, 1000, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, 0, PDO::PARAM_INT);
$statement->execute();

// Third insert.
$sql =
    'INSERT INTO ' .
    '`CashDB..cashaccount` ' .
    '(`id`, `UserNum`, `Cash`, `CashBonus`, `UpdateDateTime`) ' .
    'VALUES ' .
    '(?, ?, ?, ?, GETDATE())';
$statement = $pdo->prepare($sql);
$bindIndex = 1;
$statement->bindValue($bindIndex++, $id, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, $userNum, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, 0, PDO::PARAM_INT);
$statement->bindValue($bindIndex++, 0, PDO::PARAM_INT);
$statement->execute();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM