Query question

Hi,

I am trying to run a query in code behind, because the query is simple, I do not want to create a sp just for that. Here is my code. It runs well without a parameter.


        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conn"].ToString());

        SqlCommand cmd = new SqlCommand("SELECT CategoryName from Category ORDER BY CategoryName="  + Session["sCMID"], con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        da.Fill(table);

        ContactName.DataSource = table;
        ContactName.DataValueField = "CategoryName";
        ContactName.DataTextField = "CategoryName";
        ContactName.DataBind();


        con.Close();

Open in new window


The result will be loaded into a dropdown list.  thAnks
mcrmgAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Dustin SaundersDirector of OperationsCommented:
You should make that a method so you can reuse it.

        public static DataTable GetSelectResults(string sqlQuery, string cs)
        {
            DataTable dT = new DataTable();
            
            using (SqlConnection _cs = new SqlConnection(cs))
            {
                _cs.Open();
                SqlCommand cmd = new SqlCommand(sqlQuery, _cs);

                SqlDataAdapter dA = new SqlDataAdapter(cmd);
                dA.Fill(dT);
            }
            return dT;
        }

Open in new window


You really should paramaterize your queries to avoid issues like an injection attack.  You can also put your combo box (or whatever control) code into a method to reuse as well.

public static FillCombo(DataTable table, ComboBox comboBox, string displayColumn, string valueColumn)
{
     comboBox.DataSource = table;
     comboBox.DisplayMember = displayColumn;
     comboBox.ValueMember = valueColumn;
}

Open in new window



If you're going to run static queries from code, you might also consider creating a separate class to put those in one place to make it easier to edit/modify/add.

public static class Queries
{
     public static string GetThisQuery()
     {
          return @"SELECT * FROM Table WHERE Column = Value";
     }
}

Open in new window


And get the queries as
Queries.GetThisQuery()

Open in new window

0
käµfm³d 👽Commented:
What is the question here?
0
mcrmgAuthor Commented:
I need help with passing the parameter. thanks
0
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

mcrmgAuthor Commented:
The code works fine

SqlCommand cmd = new SqlCommand("SELECT CategoryName from Category ORDER BY CategoryName=", con);

But when I try to add parameter, it does not work

SqlCommand cmd = new SqlCommand("SELECT CategoryName from Category ORDER BY CategoryName="  + Session["sCMID"], con);

thanks
0
johnsoneSenior Oracle DBACommented:
From a database perspective, that isn't a valid query.  I'm surprised the first one runs.  There is no = in an ORDER BY.

I would think you need something like this:

SqlCommand cmd = new SqlCommand("SELECT CategoryName from Category WHERE CategoryName = "  + Session["sCMID"] + "ORDER BY CategoryName", con);

Although, I would think that CATEGORYNAME isn't the column you are filtering on, you would need to put the correct name in the WHERE.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Dustin SaundersDirector of OperationsCommented:
Well, you have some issues.

First off, if you're using VARCHAR and not using parameter, you should include the single quotes.
"SELECT * FROM Table WHERE StringValue = '" + variable + "'";

Open in new window


Secondly,
SELECT CategoryName FROM Category ORDER BY CategoryName = @variable 

Open in new window

is not proper syntax.  Are you trying to do a WHERE clause?

Thirdly, that isn't a parameterized query.  You would need to do a query like:
"SELECT CategoryName FROM Category WHERE CategoryName = @categoryName"

Open in new window

And then parameterize it.  But you should also add in to your SQL method passing a list of parameters and then inserting them to the SqlCommand.
0
mcrmgAuthor Commented:
I do not know what I was thinking...  Where is the "WHERE clause"...............
0
mcrmgAuthor Commented:
thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.