-2

I have a SQL command:

string keyProcesses = "SELECT distinct STUFF((SELECT ', '+ cn.name  from WMCCMCategories cn  INNER JOIN CategorySets uc ON uc.categoryId = cn.categoryID INNER JOIN KeyProcesses u ON u.categorySetId = uc.setId  INNER JOIN Companies c ON c.companyId = u.companyId  WHERE c.companyName = @companyName  ORDER BY cn.name FOR XML PATH('')), 1, 1, '') AS listStr FROM WMCCMCategories cnn Group by cnn.name";

And I have:

public SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandText = commandText; //where commandText is another SQL statement
sqlCmd.Parameters.Clear();

Then I execute connection:

string connectionString = ConfigurationSettings.AppSettings["connectionString"];
using (SqlConnection connection = new SqlConnection(connectionString))
{
    SqlCommand command = new SqlCommand(commandText, connection);
    try
    {
        connection.Open();
        SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
        DataTable dt=new DataTable();
        sdr.Fill(dt)

After that I want to move to the next SQL command and add parameter to that command:

sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
SqlDataAdapter sdr1 = new SqlDataAdapter(sqlCmd.CommandText, connection);
DataTable dtb1 = new DataTable();
sdr1.Fill(dtb1);

But it fail to execute this SqlCommand. I already make sure that the SQL key process can run properly with a fix parameter pre-added in. The compnName is not empty. The only suspect here is how to add value to sql parameter. I don't know what is wrong in my way of using it ?

Edit: I update the whole part of code for the easy of investigating the issue:

string connectionString = ConfigurationSettings.AppSettings["connectionString"];
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlCommand command = new SqlCommand(commandText, connection);

                try
                {
                    connection.Open();

                    SqlDataAdapter sdr = new SqlDataAdapter(sqlCmd.CommandText, connection);
                    DataTable dt=new DataTable();
                    sdr.Fill(dt);
                        //To store the values of company names:
                    List<CompanyModel> companies = new List<CompanyModel>();


                        for(int i = 0; i < dt.Rows.Count; i++)
                        {
                            companies.Add(new CompanyModel 
                            { 
                                compnSN = i + 1,
                                compnName =  dt.Rows[i]["companyName"].ToString(),
                                compnAddress =  dt.Rows[i]["address"].ToString()
                            });
                        }

                        companyRepeater.DataSource = companies;
                        companyRepeater.DataBind();

                        string comName = dt.Rows[0]["companyName"].ToString();
                        var names = companies.Select(c => c.compnName);

                        string[] arr = names.ToArray();
                        foreach (string compnyName in arr)
                        {
                            //To write names to file for debugging purpose
                            using (StreamWriter _testData = new StreamWriter(Server.MapPath("~/File.txt"), true))
                            {

                                _testData.WriteLine(compnyName); // Write the file.
                            }


                              //Get KeyProcesses
                              sqlCmd.CommandText = keyProcesses;
                              //sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
                              sqlCmd.Parameters.Add("@companyName", SqlDbType.NVarChar);
                              sqlCmd.Parameters["@companyName"].Value = compnyName;
                             // SqlDataAdapter sdr1 = new SqlDataAdapter(sqlCmd.CommandText, connection);
                              DataTable dtb1 = new DataTable();
                              //sdr1.Fill(dtb1);
                              using (var reader = sqlCmd.ExecuteReader())
                              {
                                  dtb1.Load(reader);
                              }

                              companies.Add(new CompanyModel
                              {
                                  compnKeyProcesses = dtb1.Rows[0][0].ToString()

                              });
6
  • Isn't there a typo ? cfr "compnyName" in sqlCmd.Parameters.AddWithValue("@companyName", compnyName); Commented Jun 2, 2014 at 8:16
  • What is the error? Why don't you just use a new object? Commented Jun 2, 2014 at 8:18
  • 2
    Personally, I would strongly suggest that DataTable is of little benefit here. DataTable was useful for migrating from ADO.NET record sets; however, that was 10 years ago. It should not be your default data tool (except for a few scenarios involving unknown schemas). I would strongly suggest moving to a more object-based approach for data. Commented Jun 2, 2014 at 8:22
  • 1
    I suppose that SqlCommand command is just a typo? It should be SqlCommand sqlCmd Commented Jun 2, 2014 at 10:02
  • Looks like you pointed out my problem ! Commented Jun 2, 2014 at 10:16

2 Answers 2

1

Frankly, you don't need the adapter here at all. It adds only confusion. Remove it:

sqlCmd.CommandText = keyProcesses;
sqlCmd.Parameters.AddWithValue("@companyName", compnyName);
using(var reader = sqlCmd.ExecuteReader()) {
    dtb1.Load(reader);
}
Sign up to request clarification or add additional context in comments.

16 Comments

I already try without adapter, Use, using as you said, what is the difference to that ?
@user1314404 and what happened when you did that? it should work fine. If you are asking "what does the using do?" - it ensures that the reader is disposed after use. (almost) all use of IDisposable objects should make use of using - that includes connections and commands too. And lots of other things.
Oh, I mean will this help to make sure the value will be added to the sql ? I want to use adapter because I can use sdr1.Fill)dtb1), that command make sure that I have the first record. If I use dtb1.Load(reader) I think I miss the first record.
@user1314404 and I look at your question May 29th, and you are, sure enough, doing sqlReader.Read(); dt.Load(sqlReader);. And guess what: I told you about it then: stackoverflow.com/questions/23929374/…
@user1314404 sql parameterization is not based on string-replace. It is expected that the final SQL includes @companyName. The database server knows how to handle parameters, and is given the command and parameter values separately.
|
0

sqlCmd.Parameters.Add("@companyName", SqlDbType.NVarchar(1000)); // or whatever type your database column has

sqlCmd.Parameters["@companyName"].Value = compnyName;

this is a more secure way and might help

1 Comment

It doesn't help, sorry! I got the same problem, it will not run inside the loading result to datatable, but it run to the catch exception, as I mention in my comment on Marc's answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.