代码之家  ›  专栏  ›  技术社区  ›  cal5barton

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

  •  0
  • cal5barton  · 技术社区  · 12 年前

    我正在开发一个应用程序,它要求我找到登录用户的用户名,查询用户名=活动用户的员工表,然后返回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
    

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

    我准备把我所有的头发都拔出来!请帮忙!

    2 回复  |  直到 12 年前
        1
  •  0
  •   Moho    12 年前

    这个 DbParameter 类有一个 Direction 属性,可以将值设置为 ParameterDirection.Output

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

        2
  •  0
  •   cal5barton    12 年前

    我能够用这个代码解决我的问题:

    MembershipUser user = Membership.GetUser();
        string activeuser = user.UserName;
    
        using (System.Data.SqlClient.SqlConnection sc1 =
                 new System.Data.SqlClient.SqlConnection(@"Data Source=DRIFT\GANDALF;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;