【问题标题】:How to create a stored procedure that return error message and print that error message using message box from front end如何创建一个返回错误消息并使用前端消息框打印该错误消息的存储过程
【发布时间】:2016-08-16 14:36:32
【问题描述】:

我有以下存储过程:

alter procedure [usp_chkuseridpwd]
as
begin
    declare 
        /*variable declaration */
        @sql as varchar(max),
        @tblname varchar(max),
        @user_name varchar(max),
        @user_password varchar(max),
        @response varchar(max),
        @count int,
        @passwd as varchar(max),
        @temppasswd as varchar(max)

    set @sql = 'select COUNT(*) from user_master where USER_NAME like '+@user_name+' and pasword like '+@user_password+''

    exec(@sql)

    if(@count > 0)
    begin
        set @temppasswd=('select password from user_master where USER_NAME='+@user_name+'')

        if (@temppasswd = @passwd)
            set @response=('the password is incorrect !')

        print @response //here I want to return response using message box
    end
    else 
        set @response = ('The user Id is not available')

    print @response //here I want to return response using message box
end

这里我有以下函数发送一些参数,如表名、用户名、密码(如果存储过程返回 false,则应该显示“无效用户名”,否则“用户是有效用户”)

public DataTable chkuseridpwd(ref string tname,ref string uname,ref string pwd)
{
    try
    {
        if (cnn.State == System.Data.ConnectionState.Closed)
        {
            cnn.Open();

            cmd = new SqlCommand("usp_chkuseridpwd", cnn);
            cmd.CommandTimeout = 5000;
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.AddWithValue("@tblname", tname);
            cmd.Parameters.AddWithValue("@user_name", uname);
            cmd.Parameters.AddWithValue("@user_password", pwd);

            da = new SqlDataAdapter(cmd);
            da.Fill(dtTbl);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    {
        cnn.Close();
    }

    return dtTbl;
}

【问题讨论】:

    标签: c# sql-server stored-procedures


    【解决方案1】:
    【解决方案2】:

    使用SQL Server的这个RAISERROR函数

    RAISERROR('Here Your Error Message')
    

    根据您的代码使用RAISERROR(@response)

    您将在前端将其作为异常消息捕获

    【讨论】:

    • 引发错误以返回操作想要的消息不是一件好事。在这种情况下,输出变量将起作用。
    • 先生还有 1 个问题,我应该更改方法的数据类型吗?
    • 如果你能在不引发错误的情况下处理事情,你应该先这样做。 @Vivek 您应该阅读有关输出参数的信息。
    猜你喜欢
    • 2016-01-21
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 2013-11-25
    • 2014-10-15
    • 2012-01-25
    相关资源
    最近更新 更多