protected void btnOK_Click(object sender,EventArgs e)
        {
        string strProductId,strName,strCategoryID,strDescn,strImage;
        string strConn = "",strSql = "";
        strProductId = TextBox1.Text;
        strCategoryID = TextBox2.Text;
        strName = TextBox3.Text;
        strDescn = TextBox4.Text;
        strImage = TextBox4.Text;
        try 
            {
        strConn = ConfigurationManager.ConnectionStrings["MSPetShop4ConnectionString2"].ToString();
        SqlConnection TempConn = new SqlConnection(strConn);
        SqlCommand SqlComm = new SqlCommand("addbale",TempConn );
        SqlComm.CommandType = CommandType.StoredProcedure;
        SqlParameter ProductID = SqlComm.Parameters.Add("@ProductID",SqlDbType.VarChar,10);
        ProductID.Value = strProductId;
        SqlParameter CategoryID = SqlComm.Parameters.Add("@CategoryID",SqlDbType.VarChar,10);
        CategoryID.Value = strCategoryID;
        SqlParameter Name = SqlComm.Parameters.Add("@Name",SqlDbType.VarChar,80);
        Name.Value = strName;
        SqlParameter Descn = SqlComm.Parameters.Add("@Descn",SqlDbType.VarChar,255);
        Descn.Value = strDescn;
        SqlParameter Image = SqlComm.Parameters.Add("@Image",SqlDbType.VarChar,80);
        Image.Value = strImage;
            TempConn.Open( );
         }
        
        catch
            {
            throw new ArgumentNullException( );
            }该段代码。如果数据合法的话,能顺利插入一条记录,但是如果用户输入了受外键约束的非法数据,插入记录将失败。但是怎么在客户端判断,记录是否插入成功了,存储过程中倒是做了判断,但是无法在C#代码中获取存储过程的错误代码?存储过程如下:Create procedure  addbale
@ProductId varchar(10),
@CategoryId varchar(10),
@Name varchar(80),
@Descn varchar(255),
@Image varchar(80)
as
begin
INSERT INTO Product VALUES(@ProductId,@CategoryId,@Name,@Descn,@Image)if @@ROWCOUNT=0 
begin
raiserror('error',16,1)
rollback transaction
endend

解决方案 »

  1.   

    一般我的做法是传参数进去,Create procedure  addbale 
    @ProductId varchar(10), 
    @CategoryId varchar(10), 
    @Name varchar(80), 
    @Descn varchar(255), 
    @Image varchar(80),
    @Result int out        --参数
    as 
    begin
    set @Result =0         --初始化
    INSERT INTO Product VALUES(@ProductId,@CategoryId,@Name,@Descn,@Image) if @@ROWCOUNT=0  
    begin 
    set @Result =1
    raiserror( 'error ',16,1) 
    rollback transaction 
    end end 代码里面接收到 @Result 的值来判断
      

  2.   

    如果在存储过程中使用raiserror( 'error ',16,1) 的方法返回信息,那么在程序上只能通过捕获异常来得到,比如:try
    {
        //操作代码
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }你可以通这在存储过程中添加输出参数来把存储过程中的信息返回到程序里,比如:
    Create procedure  addbale 
        @strMessage varchar(10) output,
        ... 
    as 
    if error<>0
    begin 
        set @strMessage="error message";
        rollback transaction 
    end 在程序里通过SqlParameter.Direction的值为Output来获取这个信息
      

  3.   

    哦,感谢二位,这招明白了,还有别的狠招吗?感觉sqlcommand在和数据库交互的时候,应该能带点什么回来啊。