运行SqlCommand.ExecuteScalar后,事务变为空

时间:2017-11-10 05:49:37

标签: c# sqlclient

我在SQL Server中有一个表定义如下

getNodes()

当我使用ID(具有错误的数据类型,它是create table Customer (ID varchar(10), Name varchar(200)) Insert into Customer values ('00001', 'Cust1'), ('ID00002', 'Cust2') ,但它的值传递为varchar)查询客户名称时,该命令返回正确的名称,但其事务变为空,并且试图提交,我收到错误

  

出现InvalidOperationException
  这个SqlTransaction已经完成;它不再可用了。

我的代码:

int

我可以做些什么来检查这种情况,并在命令执行时失败,而不是在后期获得异常?

1 个答案:

答案 0 :(得分:-1)

当输入表达式求值为有效的数值数据类型时,ISNUMERIC返回1;否则它返回0.

您尝试此代码

  using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["SchoolPlusDBContext"].ConnectionString))
        {
            conn.Open();

            using (var trans = conn.BeginTransaction())
            {
                using (var cmd = new SqlCommand("SELECT Name FROM Customer where  ISNUMERIC(id)=1 and Id=1")) // After this command is executed, its transaction becomes null.
                //using (var cmd = new SqlCommand("SELECT Name FROM Customer  WHERE ID = '000001'")) // This runs fine.
                {
                    cmd.Connection = conn;
                    cmd.Transaction = trans;
                    var res = cmd.ExecuteScalar();
                }

                trans.Commit();
            }
        }