在PHP中,要从MSSQL数据库获取插入ID,可以使用以下方法:
@@IDENTITY
查询在执行插入操作后,可以使用@@IDENTITY
查询来获取插入行的ID。以下是一个示例:
<?php
$serverName = "serverName";
$connectionOptions = array(
"Database" => "databaseName",
"Uid" => "username",
"PWD" => "password"
);
// 连接到MSSQL数据库
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
// 插入数据
$sql = "INSERT INTO tableName (column1, column2) VALUES ('value1', 'value2')";
$insertQuery = sqlsrv_query($conn, $sql);
if($insertQuery === false) {
die(print_r(sqlsrv_errors(), true));
}
// 获取插入ID
$sql = "SELECT @@IDENTITY AS 'InsertedID'";
$insertIDQuery = sqlsrv_query($conn, $sql);
if($insertIDQuery === false) {
die(print_r(sqlsrv_errors(), true));
}
// 打印插入ID
while($row = sqlsrv_fetch_array($insertIDQuery, SQLSRV_FETCH_ASSOC)) {
echo "Inserted ID: " . $row['InsertedID'];
}
// 关闭连接
sqlsrv_close($conn);
?>
SCOPE_IDENTITY()
查询SCOPE_IDENTITY()
函数与@@IDENTITY
类似,但它仅返回当前作用域内的插入ID。这在处理触发器或存储过程时可能更有用。以下是一个示例:
<?php
$serverName = "serverName";
$connectionOptions = array(
"Database" => "databaseName",
"Uid" => "username",
"PWD" => "password"
);
// 连接到MSSQL数据库
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
// 插入数据
$sql = "INSERT INTO tableName (column1, column2) VALUES ('value1', 'value2')";
$insertQuery = sqlsrv_query($conn, $sql);
if($insertQuery === false) {
die(print_r(sqlsrv_errors(), true));
}
// 获取插入ID
$sql = "SELECT SCOPE_IDENTITY() AS 'InsertedID'";
$insertIDQuery = sqlsrv_query($conn, $sql);
if($insertIDQuery === false) {
die(print_r(sqlsrv_errors(), true));
}
// 打印插入ID
while($row = sqlsrv_fetch_array($insertIDQuery, SQLSRV_FETCH_ASSOC)) {
echo "Inserted ID: " . $row['InsertedID'];
}
// 关闭连接
sqlsrv_close($conn);
?>
这些方法可以帮助您在PHP中从MSSQL数据库获取插入ID。
领取专属 10元无门槛券
手把手带您无忧上云