将SQL查询结果分配给会话变量

时间:2015-11-13 09:52:37

标签: c# sql asp.net sql-server

我正在尝试根据谁登录获取WITH Unpivoted AS ( SELECT Code, Fields, [Value] FROM #T_shirt_sizes UNPIVOT( [Value] FOR Fields IN( [Length],[Chest],[Shoulder],[Sleeve Length])) AS u ) SELECT Fields AS [T-Shirt], [XXXS], [XXS], [XS], [S], [M],[L] FROM Unpivoted PIVOT ( MAX([Value]) FOR Code IN([XXXS], [XXS], [XS], [S], [M],[L])) AS piv; 并将其分配给会话变量来运行SQL查询。我无法将结果分配给变量。

Team_ID

1 个答案:

答案 0 :(得分:0)

你的代码没有多大意义......

如果您想要Team_ID - 为什么要先加载整行,然后再次调用数据库 得到Team_ID ???

我试图简化你的代码:

protected void ButtonLogin_Click(object sender, EventArgs e)
{
    // check what user category was selected and login to appropriate page
    if (DropDownListUserType.SelectedIndex == 1)
    {
        // define connection string and SQL query as strings
        string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
        string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = @username AND Password_1 = @password";

        // set up SqlConnection and SqlCommand in "using" blocks
        using (SqlConnection con = new SqlConnection(connectionString))
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            // define and fill parameters - DO NOT use .AddWithValue!
            cmd.Parameters.Add("@username", SqlDbType.VarChar, 100).Value = UserName.Text;
            cmd.Parameters.Add("@password", SqlDbType.VarChar, 100).Value = Password.Text;

            // open connection, execute scalar, close connection
            con.Open();

            object result = cmd.ExecuteScalar();

            // if we got back a result ....
            if(result != null)
            {
                int teamID = Convert.ToInt32(result.ToString());

                Session["Team_ID"] = teamID;
                Response.Redirect("AddPlayer.aspx");
            }
            else 
            {
                // if result is NULL, then the username+password
                // were NOT found - do what needs to be done in that case here
            }
        }
    }
}