C# 调用存储过程 Sql Server存储过程 存储过程报错,程序中的try

C#程序调用Sql Server存储过程,存储过程中报错情况,返回值...

0.SQL存储过程

USE [Opos]
GO
/****** Object:  StoredProcedure [dbo].[Test]    Script Date: 2017/4/17 10:38:54 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[Test]
    @NameTest Varchar(10)--程序中将这个值写的很大的话,报错"将截断字符串或二进制数据。"
AS
BEGIN
    Begin Tran

    Begin Try
        Declare @TestTab Table(Name Nvarchar(1),ID Int)
        --不是在Catch中报错...
        If(@NameTest = '')
            Begin
                Insert @TestTab
                Select @NameTest,0
                --本来将错误严重级定为[19],程序Catch报错↓
                --大于 18 的错误严重级别只能由 sysadmin 角色的成员用 WITH LOG 选项指定。
                --Raiserror('Name 不可为空 ...',19,100)
                /*貌似这里自定义的错误,程序catch中不报错...*/
                Raiserror('Name 不可为空 ...',10,100)
            End
        

        Insert @TestTab
        Select @NameTest,0


        Select * From @TestTab
        --提交事务
        Commit Tran
        Return 1

    End Try

    Begin Catch
        Declare @Error_Msg Nvarchar(4000),@Error_Severity Int

        Select @Error_Msg = Error_message(),@Error_Severity = ERROR_SEVERITY()
        --回滚事物
        Rollback Tran
        --报错
        Raiserror(@Error_Msg,@Error_Severity,100)
        --返回值
        Return 0
    End Catch


END

1.C# code

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows;

namespace CProcedureReturn
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }



        private void RunProcedure(object sender, RoutedEventArgs e)
        {
            try
            {
                string name_test = "304985039480598304985039840583409853409098098098098098";
                SqlParameter[] pars = {
                new SqlParameter("@NameTest",name_test)
                };
                //DataSet ret_tab = db.RunProcedure("[csms].[spClassTableGenerateZixi]", pars, "ret_tab");
                //受影响的行数...
                int affect_rows_count = 0;
                //存储过程的返回值...
                int result = this.RunProcedure("[dbo].[Test]", pars, out affect_rows_count);
                if (result == 1)
                {
                    MessageBox.Show("未报错,成功!");
                }
                else
                {
                    MessageBox.Show("报错!");
                }

            }
            catch (System.Data.SqlClient.SqlException sql_e)
            {
                MessageBox.Show(sql_e.Message);
            }
        }





        #region SQL一些函数
        //连接数据库的字符串...
        public static string connectionString = "server=.;database=Opos;uid=sa;pwd=1234";

        /// <summary>
        /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值)
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand</returns>
        private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {

            SqlCommand command = new SqlCommand(storedProcName, connection);
            command.CommandType = CommandType.StoredProcedure;
            foreach (SqlParameter parameter in parameters)
            {
                if (parameter != null)
                {
                    // 检查未分配值的输出参数,将其分配以DBNull.Value.
                    if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                        (parameter.Value == null))
                    {
                        parameter.Value = DBNull.Value;
                    }
                    command.Parameters.Add(parameter);
                }
            }

            return command;
        }


        /// <summary>
        /// 创建 SqlCommand 对象实例(用来返回一个整数值)    
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <returns>SqlCommand 对象实例</returns>
        private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
        {
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.Parameters.Add(new SqlParameter("ReturnValue",
                SqlDbType.Int, 4, ParameterDirection.ReturnValue,
                false, 0, 0, string.Empty, DataRowVersion.Default, null));
            return command;
        }


        /// <summary>
        /// 执行存储过程,返回影响的行数        
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="rowsAffected">影响的行数</param>
        /// <returns></returns>
        public int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                int result;
                connection.Open();
                SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
                rowsAffected = command.ExecuteNonQuery();
                result = (int)command.Parameters["ReturnValue"].Value;
                //Connection.Close();
                return result;
            }
        }

        /// <summary>
        /// 执行存储过程
        /// </summary>
        /// <param name="storedProcName">存储过程名</param>
        /// <param name="parameters">存储过程参数</param>
        /// <param name="tableName">DataSet结果中的表名</param>
        /// <returns>DataSet</returns>
        public DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                DataSet dataSet = new DataSet();
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();

                SqlCommand sql_command = new SqlCommand();
                sql_command = BuildQueryCommand(connection, storedProcName, parameters);


                sqlDA.SelectCommand = sql_command;//BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet, tableName);
                connection.Close();
                return dataSet;
            }
        }

        #endregion



    }
}

 

x

测试了下
RAISERROR ( '错误消息', 16, 1)可以在异常中捕获

 

x

 

posted @ 2017-05-01 21:56  zh89233  阅读(2496)  评论(0编辑  收藏  举报