无法弄清楚如何使用 SQL 数据源 ASP.Net 将输出的参数存储到变量



我正在开发一个应用程序,它要求我查找登录用户的用户名,查询用户名=活动用户的雇员表,然后返回EmployeeID、TeamID和PositionID来设置会话状态变量,以根据每个用户创建不同的视图。

我创建了这个存储过程来输出所需的参数。

CREATE PROCEDURE ASP_UserSession @Username nvarchar(256), @UserID int OUTPUT, @TeamID int OUTPUT, @PositionID int OUTPUT
AS
SELECT @UserID = ID, @TeamID = TeamID, @PositionID = PositionID
FROM Employee
WHERE UserName = @Username

现在我遇到的问题是将输出参数存储到代码文件中,以便在会话状态中设置参数。

我都快把头发都拔出来了!请帮助!

DbParameter类具有Direction属性,可设置ParameterDirection.Output

执行存储过程后,从命令对象的参数集合中获取参数对象并获取其值。

我可以用下面的代码修复我的问题:

MembershipUser user = Membership.GetUser();
    string activeuser = user.UserName;
    using (System.Data.SqlClient.SqlConnection sc1 =
             new System.Data.SqlClient.SqlConnection(@"Data Source=DRIFTGANDALF;Initial Catalog=Wizard_Swears;" +
                 "Integrated Security=True"))
    {
        sc1.Open();
        using (System.Data.SqlClient.SqlCommand command1 = new System.Data.SqlClient.SqlCommand())
        {
            command1.CommandType = CommandType.Text;
            command1.Connection = sc1;
            // DIRECTION :: Input
            command1.CommandText = "select @UserID = [ID], @TeamID = [TeamID], @PositionID = [PositionID] FROM [Employee] WHERE ([UserName] = @UserName)";
            System.Data.SqlClient.SqlParameter paramter1 = command1.Parameters.Add("@UserName", activeuser);
            System.Data.SqlClient.SqlParameter paramter2 = command1.Parameters.Add("@UserID", SqlDbType.SmallInt);
            System.Data.SqlClient.SqlParameter paramter3 = command1.Parameters.Add("@TeamID", SqlDbType.SmallInt);
            System.Data.SqlClient.SqlParameter paramter4 = command1.Parameters.Add("@PositionID", SqlDbType.SmallInt);
            paramter1.Direction = ParameterDirection.Input;
            paramter2.Direction = ParameterDirection.Output;
            paramter3.Direction = ParameterDirection.Output;
            paramter4.Direction = ParameterDirection.Output;
            command1.ExecuteNonQuery();
            //Store values to variables to be set to session
            string userID = paramter2.Value.ToString();
            string teamID = paramter3.Value.ToString();
            string positionID = paramter4.Value.ToString();
            UserIDLBL.Text = userID;
            TeamIDLBL.Text = teamID;
            PositionIDLBL.Text = positionID;

            Session["Username"] = activeuser;
            Session["UserID"] = UserIDLBL.Text;
            Session["AMID"] = TeamIDLBL.Text;
            Session["PositionID"] = PositionIDLBL.Text;

最新更新