在SQL Server中为自动增量ID设置MAX

时间:2016-11-21 19:45:16

标签: sql sql-server insert auto-increment

我有一个从数据库表中导入221行的表。每当我在HTML Table页面中动态添加一行时,我希望它能够拉出MAX ID,所以在这种情况下221,并添加1,因此将MR_ID带到222.我需要这个因为每个ID必须独一无二。每当我在表中添加一行并在数据库中查看它时,它就会显示为NULL。我有一些东西,但它似乎没有工作。如果您需要的代码多于我发布的代码,请告诉我,我会提供。谢谢!

<?php

  $MR_ID = $_POST['MR_ID'];
  $MR_Name = $_POST['MR_Name'];
  $Buyer_ID = $_POST['Buyer_ID'];
  $MR_POC_N = $_POST['MR_POC_N'];
  $MR_POC_E = $_POST['MR_POC_E'];
  $MR_POC_P = $_POST['MR_POC_P'];

  $host="xxxxxxx"; 
  $dbName="xxxx"; 
  $dbUser="xxxxxxxxxxx"; 
  $dbPass="xxxxxxxxx";

  $pdo = new PDO("sqlsrv:server=".$host.";Database=".$dbName, $dbUser, $dbPass);

  $MR_ID = "Select MAX(MR_ID) + 1 FROM Stage_Rebate_Master";
  $sql = "INSERT INTO Stage_Rebate_Master (MR_ID, MR_Name, Buyer_ID, MR_POC_N, MR_POC_E, MR_POC_P) VALUES (?, ?, ?, ?, ?, ?)";
  $stmt = $pdo->prepare($sql);
  $result = $stmt->execute(array($MR_ID, $MR_Name, $Buyer_ID, $MR_POC_N, $MR_POC_E, $MR_POC_P));
  echo json_encode($result);

?>

1 个答案:

答案 0 :(得分:0)

你可以这样尝试

$sql = "INSERT INTO Stage_Rebate_Master (MR_ID, MR_Name, Buyer_ID, MR_POC_N, MR_POC_E, MR_POC_P) SELECT  ISNULL(MAX(MR_ID)+1,1), ?, ?, ?, ?, ? FROM Stage_Rebate_Master";
$stmt = $pdo->prepare($sql);
$result = $stmt->execute(array( $MR_Name, $Buyer_ID, $MR_POC_N, $MR_POC_E, $MR_POC_P));