【问题标题】:Executing an insert statement and put id in a local variable?执行插入语句并将 id 放入局部变量中?
【发布时间】:2012-04-28 23:51:56
【问题描述】:
SqlDataSource myQuiz = new SqlDataSource();

myQuiz.ConnectionString = ConfigurationManager.ConnectionStrings["yafnet"].ToString();
myQuiz.InsertCommand = "INSERT INTO [QuizTable]([Quiz_Title],[Quiz_Description]) VALUES (@Quiz_Title,@Quiz_Description)";

myQuiz.InsertParameters.Add("Quiz_Title",Quiz_Title.Text);
myQuiz.InsertParameters.Add("Quiz_Description",Quiz_Description.Text);

myQuiz.Insert();
Response.Redirect("QuizQuests.aspx");

有没有办法取回自动生成的新行 ID 并放入局部变量中?

提前非常感谢, 阿德里安

【问题讨论】:

标签: c# sql-server


【解决方案1】:

使用

SELECT IDENT_CURRENT(‘QuizTable’)

它返回表中生成的最后一个 IDENTITY 值,与创建该值的连接无关,也与生成该值的语句的范围无关。 IDENT_CURRENT 不受范围和会话限制;它仅限于指定的表。 IDENT_CURRENT 返回为任何会话和任何范围内的特定表生成的标识值。

【讨论】:

  • 但是如果另一个会话在您的插入之后但在您的IDENT_CURRENT 调用之前插入QuizTable,您将获得另一个插入的标识值,而不是您的(参见@987654321 @了解详细信息)
【解决方案2】:

如果您想 100% 确定您确实从实际 QuizTable 中的插入中获得身份,您应该使用 SCOPE_IDENTITY()(正如 Luiggi Mendoza 在他的评论中已经提到的),而不是 @@IDENTITYIDENT_CURRENT

@@IDENTITY 可能无法工作,因为it will return the identity from the last insert that happened from your connection。因此,如果您的QuizTable 上有一个触发器,它在另一个具有标识列的表中插入一行,@@IDENTITY 将返回第二次插入的值,而不是原始插入到QuizTable 中的值.

IDENT_CURRENT 将返回您的表的最后一个标识值(并且仅适用于您的表,因此是否存在像上一个示例中那样的触发器并不重要)。
但它会返回 any 会话的最后一个身份值。因此,如果从您的 INSERT 和您的 IDENT_CURRENT 之间的另一个会话中插入另一行,you'll get the identity value from that row, not from yours.

【讨论】:

    【解决方案3】:

    @Adrian De Barro:您好,您可以使用以下代码获取插入的记录 ID 并保存在变量中

    在您的 sqlquery 中添加以下语句:

    return @@IDENTITY
    

    你的 C# 代码如下:

        SqlConnection cn = new   
        SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);        
        cn.Open();
        SqlCommand cmd = new SqlCommand(procname, cn);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlParameter str = new SqlParameter("name", SqlDbType.VarChar);
        str.Direction = ParameterDirection.ReturnValue;
        foreach (SqlParameter par in param)
        {
            cmd.Parameters.Add(par);
        }
        string name = Convert.ToString(cmd.ExecuteScalar());
        cmd.Dispose();
        cn.Close();
        return name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      相关资源
      最近更新 更多