简体   繁体   中英

How to use a parameter for a SQL Server query that is part of the query itself using SqlDataReader in C# asp.net

Background

I am trying to retrieve the count of occurrences of a user in the database at the same time as returning the data set. How do I accomplish this? My code is below of what I have so far.

If I hard code the username, for the row, I get the expected output. However, I am having problems declaring a parameterized query variable with this code. Any help would be appreciated. I have been working on this for quite some time now.

protected void Page_Load(object sender, EventArgs e)
{
    string ConnStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

    using (SqlConnection conn = new SqlConnection(ConnStr))
    {
        string Command = "SELECT TOP 3 *, Counter = (select Count(User) from Projects where [User]='jmoore00' AND Account = 'ACTIVE') FROM Projects";

        using (SqlCommand comm = new SqlCommand(Command, conn))
        {
            conn.Open();  

            SqlDataReader rdr = comm.ExecuteReader();

            ListView.DataSource = rdr;
            ListView.DataBind();

            rdr.Close();
        }
    }
}

Above, 'jmoore00' should be scalar variable @User but how do I appropriately declare and use the variable with value equaling rdr["user"] if I am using the code the way it is?

I think you should use Stored Procedure in you sql.as a specific user try to retrieve its data, do add number of this occurrence to a field in your sql. each user has a unique field which can be in access with their users or userID. but i think it will increase transaction time .

hope it would be helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM