首先,简要介绍一下我们需要什么?

我们想在sql中用 try...catch,如果成功,就返回我们查询的值,如果失败就返回-1

所以有了以下sql语句(写在后台的)

                    string myInsert = @"begin try 
                                            insert into dbo.Categories values(@categoryName);
                                            set @result = (select @@identity id); //设置成功返回值,这儿是我们查询自增id
                                        end try 
                                        begin catch 
                                            set @result = -1;//设置失败返回值-1
                                        end catch";

Sql语句已经写好,现在就是需要获取到这个@result,后台代码可以参考一下

                     //定义一个数据库执行指令
                    SqlCommand insertCommand = new SqlCommand(myInsert, myConnection);
                    //添加集合
                    insertCommand.Parameters.Add(new SqlParameter() { ParameterName = "categoryName", Value = catename});
                    //获取到result返回值,主要是这个Output
                    insertCommand.Parameters.Add("@result", SqlDbType.Int).Direction = ParameterDirection.Output;
                    insertCommand.ExecuteNonQuery();
            //这个DataConvert.ToInt32是自定义方法,是把查询到的object对象转换为int
int result = DataConvert.ToInt32(insertCommand.Parameters["@result"].Value); if (result > 0) { categoryinfo.ID = result; }

 

 

 

注:此篇随笔只供参考使用,而且也有很多小瑕疵,最主要的不是代码,逻辑才是最重要的。

相关文章:

  • 2021-07-21
  • 2021-11-05
  • 2021-11-05
  • 2021-10-15
  • 2021-10-01
  • 2018-12-26
  • 2021-12-14
猜你喜欢
  • 2021-09-28
  • 2021-11-01
  • 2021-11-05
  • 2021-09-29
  • 2021-10-16
  • 2021-08-01
  • 2019-09-19
相关资源
相似解决方案