将Scope Identity插入存储过程的第二个表中

时间:2014-04-09 23:43:21

标签: .net sql-server

我将记录插入到2个不同的表中,其中包含1个存储过程。我需要获取第一个表的范围标识,并将其插入" TableId"下的第二个表中。我在下面做的不是为@Identity工作。有什么想法吗?

PROCEDURE [dbo].[campVideo]

    @DateCreated datetime,
    @CustomerId int,
    @VideoName varchar(100),
    @Identity int OUT,
    @UserID int,
    @DateTime datetime

AS  
BEGIN

Insert Into Table1 (DateCreated, CustomerId, VideoName)
    Values (@DateCreated, @CustomerId, @VideoName)
    SET @Identity = SCOPE_IDENTITY()

Insert Into Table2 (UserID, DateTime, Table1Id)
    Values (@UserID, @DateTime, @Identity)
End

aspx代码在这里:

string strConn = "mydatasource";       

    SqlConnection Conn = new SqlConnection(strConn);
    SqlCommand Cmd = new SqlCommand("campVideo", Conn);
    Cmd.CommandType = CommandType.StoredProcedure;
    Cmd.Parameters.Add(new SqlParameter("@DateCreated", DateTime.Now.ToString()));        
    Cmd.Parameters.Add(new SqlParameter("@CustomerId", strId));
    Cmd.Parameters.Add(new SqlParameter("@VideoName", flv_filename));
    Cmd.Parameters.Add(new SqlParameter("@UserID", strId));
    Cmd.Parameters.Add(new SqlParameter("@DateTime", DateTime.Now.ToString()));
    SqlParameter ClientIDSource = Cmd.Parameters.Add("@Identity", SqlDbType.Int, 0, "Id");
    ClientIDSource.Direction = ParameterDirection.Output;

2 个答案:

答案 0 :(得分:0)

您是否尝试使用IDENT_CURRENT而不是SCOPE_IDENTITY()

试着看看here

*" SCOPE_IDENTITY()将返回在当前会话中创建的最后一个标识值" *

答案 1 :(得分:0)

查询中的Table1表似乎没有Identity列。 要使用SCOPE_IDENTITY()获取最新插入的ID,您需要在要插入的表中具有标识列。请参阅SQL Server Management Studio中的Table1架构验证是否存在Identity Column。

以下是样本。希望这会有所帮助:

或者,您可以在SQL小提琴中查看此内容 - http://sqlfiddle.com/#!3/a9906/3

    create table #Table1 (Table1_ID int identity(1,1),DateCreated Datetime, CustomerId int, VideoName varchar(100))
    create table #Table2 (UserID int, [DateTime] DateTime, Table1Id int)

    DECLARE @DateCreated datetime
    DECLARE @CustomerId int
    DECLARE @VideoName varchar(100)
    DECLARE @Identity int
    DECLARE @UserID int
    DECLARE @DateTime datetime


    SET @DateCreated = '2014-04-10'
    SET @CustomerId = 1
    SET @VideoName = 'videoname'
    SET @Identity = 0
    SET @UserID = 2
    SET @DateTime = '2014-04-10'

    Insert Into Table1 (DateCreated, CustomerId, VideoName) Values (@DateCreated, @CustomerId, @VideoName)


    SET @Identity = SCOPE_IDENTITY()

    SELECT @Identity as Latest_Identity_Value

    Insert Into Table2 (UserID, DateTime, Table1Id) Values (@UserID, @DateTime, @Identity) 

       select * from Table2