在新查询中使用SCOPE_IDENTITY中返回的ID

时间:2014-04-22 20:25:51

标签: php sql-server

现在,这就是我所拥有的:

$query = "INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star')"; 
mssql_query($query, $connection);
$commentIDQuery = "SELECT SCOPE_IDENTITY() AS ins_id";
$CI = mssql_query ($commentIDQuery, $connection);
$commentID = mssql_fetch_row($CI);
$idQuery = "SELECT recipeid FROM t_recipe WHERE recipename = '$recipeName'";
$RID = mssql_query($idQuery, $connection);
$recipeID = mssql_fetch_row($RID);  
$rcQuery = "INSERT INTO COMMENT_RECIPE VALUES ('$commentID[0]', '$recipeID[0]')";
    mssql_query($rcQuery, $connection);

那么我怎样才能获得ins_id?

它将它添加到第一个表,即注释,但不是关系表。

使用sql server 2008

1 个答案:

答案 0 :(得分:0)

这个怎么样......

$query = "DECLARE @NewID INT
          INSERT INTO COMMENTS VALUES ('$user', '$comment', '$star');
          SELECT @NewID  = SCOPE_IDENTITY();
          INSERT INTO COMMENTS_RECIPE VALUES (@NewID, '$recipeid')";

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