Table i need to sort
So i got this 5 drop downs i need to use for sorting output from sql
Now i use
DropDownList_Instruktorer.Items.Insert(0, new ListItem("Vælg Instruktør", "*"));
For the Default Value, and i was thinking this will do the job. But
cmd.Parameters.addwithvalue
enter the value into value obviously instead of use * to show all results like it normally does in sql
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE fk_in_id = #Instruktor AND
fk_st_id = #Stilart AND
fk_ag_id = #Aldersgruppe AND
fk_ni_id = #Niveau AND
fk_ht_id = #Tid", conn);
cmd.Parameters.AddWithValue("#Instruktor", DropDownList_Instruktorer.SelectedValue);
cmd.Parameters.AddWithValue("#Stilart", DropDownList_Stilart.SelectedValue);
cmd.Parameters.AddWithValue("#Aldersgruppe", DropDownList_Aldersgrupper.SelectedValue);
cmd.Parameters.AddWithValue("#Niveau", DropDownList_Niveauer.SelectedValue);
cmd.Parameters.AddWithValue("#Tid", DropDownList_Tider.SelectedValue);
Here is my sql, Any idea how i can i get it to work without writing 25 if statements?
Why not use a string in place of the AddWithValue, eg:
string instructorStr = "";
string stilartStr = "";
...
if (DropDownList_Instruktorer.SelectedValue != "*")
{
instructorStr = "fk_in_id = " + DropDownList_Instruktorer.SelectedValue + " AND";
}
if (DropDownList_Stilart.SelectedValue != "*")
{
stilartStr = "fk_st_id = " + DropDownList_Stilart.SelectedValue + " AND";
}
...
SqlCommand cmd = new SqlCommand(#"SELECT * FROM Hold
INNER JOIN Instruktorer
ON instruktor_id = fk_in_id
INNER JOIN Stilarter
ON stilart_id = fk_st_id
INNER JOIN Aldersgruppe
ON aldersgruppe_id = fk_ag_id
INNER JOIN Niveauer
ON niveau_id = fk_ni_id
INNER JOIN Tider
ON tid_id = fk_ht_id
WHERE " +
instructorStr +
stilartStr +
...
+ " 1 = 1", conn);
Then you have the option to do all sorts of stuff with the individual variables, including ORDER BY
Using Stringbuilder would be cleaner but it's easier to show it this way.
Related
I am creating a form that I can add a menu item to display All Suppliers and Suppliers Quantity by Part number. So I got ReportSupplierDisplayALl to work when I ran. But When I try to run the form for the ReportSuppliersDisplayByPartnumber because When I enter the SupplierID and when I did it threw an exception.
When it throws an exception, what does it mean by incorrect syntax?
public DataTable DisplaySupplierByPartNumber(string PartNumber)
{
// Add using System.Data
string queryString = "SELECT Suppliers.SupplierName, Suppliers.Email, Parts.PartName, SUM(Inventory.Quantity) AS SumOfQuantity, PartNumber " +
"FROM ((Suppliers INNER JOIN Parts ON Suppliers.SupplierID = Parts.Supplier) INNER JOIN Inventory ON Parts.PartNumber = Inventory.PartNumber " +
"INNER JOIN Employees ON Inventory.EmpID = Employees.EmpID " +
"GROUP BY Suppliers.SupplierName, Suppliers.Email, Parts.PartName, Parts.PartNumber " +
"HAVING Parts.PartNumber = #PartNumber " +
"ORDER BY Suppliers.SupplierName ";
using (SqlConnection con = new SqlConnection(_strCon))
{
try
{
SqlCommand command = new SqlCommand(queryString, con);
command.Parameters.AddWithValue("#PartNumber", PartNumber );
con.Open();
SqlDataReader reader = command.ExecuteReader();
DataTable theTable = new DataTable();
theTable.Load(reader);
return theTable;
}
catch (Exception ex)
{
throw ex;
}
}
enter image description here
enter image description here
Don't use "" For String use # "Your Query And Make Sure You get all bracket correct"
also change element take part number first then use your aggerate function
string queryString = #"SELECT S.SupplierName, S.Email, P.PartName, SUM(Inventory. Quantity) AS SumOfQuantity FROM Suppliers as s
INNER JOIN Parts as p on P.SupplierId=P.SupplierId
INNER JOIN Inventory ON Parts.PartNumber = Inventory.PartNumber
INNER JOIN Employees ON Inventory.EmpID = Employees.EmpID
GROUP BY S.SupplierName, S.Email, P.PartName, P.PartNumber
HAVING Parts.PartNumber = #PartNumber
ORDER BY S.SupplierName"
I'm executing the following code:
public ActionResult BranchUser(int ? idBranch)
{
CtrForm objCtrForm = new CtrForm();
objCtrForm.Connect();
objCtrForm.query.Connection = objCtrForm.connection;
objCtrForm.query.CommandType = CommandType.Text;
List<tblUser> listBranchUser = new List<tblUser>();
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch;
objCtrForm.query.CommandText = sql;
objCtrForm.connection.Open();
SqlDataReader sReader = objCtrForm.query.ExecuteReader();
while (sReader.Read())
{
listBranchUser.Add(
new tblUser
{
idUser = Convert.ToInt32(sReader["idUser"]),
name = Convert.ToString(sReader["name"]),
phone = Convert.ToString(sReader["phone"]),
email = Convert.ToString(sReader["email"])
}
);
}
objCtrForm.connection.Close();
return View(listBranchUser);
}
but I got the following error when I call the function:
System.Data.SqlClient.SqlException: 'Incorrect syntax near '='.'
I don't understand why I get this, due to I executed in other functions but I only called one table, not two. Any advice I will appreciate.
I believe C# won't implicitly convert an integer to a string.
Try replacing
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch;
With
string sql = #"SELECT B.name, B.phone, B.email, B.idUser FROM tblBranchUser A
INNER JOIN tblUsers B ON A.idUser = B.idUser
WHERE A.idBranch = " + idBranch.ToString();
SQL query:
SELECT som.id, som.name, som.search_enabled, oc.id, oc.name
FROM option_category oc
INNER JOIN skill_option so
on oc.id=so.option_category_id
INNER JOIN skill_option_master som
on som.id=so.id;
Works fine in Workbench:
However, within my C# code:
List<string> listItems = getMultiColumnListFromDB(
"SELECT som.id, som.name, som.search_enabled, oc.id, oc.name " +
"FROM option_category oc " +
"INNER JOIN skill_option so " +
" on oc.id=so.option_category_id " +
"INNER JOIN skill_option_master som " +
" on som.id=so.id; "
,new string[] { "som.id", "som.name", "som.search_enabled", "oc.id", "oc.name" });
...
private List<string> getMultiColumnListFromDB(string query, string[] columnNames)
{
List<string> result = new List<string>();
MySqlConnection con = new MySqlConnection(dbConnectionString);
MySqlCommand cmd = new MySqlCommand(query, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string strResult = "";
foreach (string columnName in columnNames)
{
if (reader[columnName] == DBNull.Value)
//If value is NULL, we assume yes/1
strResult = strResult + "1" + ";";
else
strResult = strResult + reader[columnName].ToString() + ";";
}
result.Add(strResult.TrimEnd(';'));
}
return result;
}
...I get: System.IndexOutOfRangeException: 'Could not find specified column in results: som.id' at Line: if (reader[columnName] == DBNull.Value)
As a test, I copied the query from the Exceptions window whilst debugging back into Workbench and it worked without any modifications required1. Simpler queries (without joins) work fine within my app. I appreciate my code isn't the most elegant but I can't get over 1 above. How can that be?
Thanks
Modified SQL query to alias the column names:
SELECT som.id as 'som.id', som.name as 'som.name', som.search_enabled as 'som.search_enabled', oc.id as 'oc.id', oc.name as 'oc.name'
FROM option_category oc
INNER JOIN skill_option so
on oc.id=so.option_category_id
INNER JOIN skill_option_master som
on som.id=so.id;
I am working with a window form application. I have an array to store a list of checkbox with different data type in it (string and integer). Below code is my checkBox checkBox A to E get the employee name and cheeckBox 1-5 get the employee favorite number.
//Array of Class and secondary Check Box
CheckBox[] myCheckBoxArray = new CheckBox[10];
myCheckBoxArray[0] = checkBoxA;
myCheckBoxArray[1] = checkBoxB;
myCheckBoxArray[2] = checkBoxC;
myCheckBoxArray[3] = checkBoxD;
myCheckBoxArray[4] = checkBoxE;
myCheckBoxArray[5] = checkBox1;
myCheckBoxArray[6] = checkBox2;
myCheckBoxArray[7] = checkBox3;
myCheckBoxArray[8] = checkBox4;
myCheckBoxArray[9] = checkBox5;
After that I am trying to bind the checkbox to my SQL database and have a foreach loop to check if anyone of these checkbox is checked. I am wondering if this is a good way to combine both integer and string array together or should I use a nested foreach loop? Because I am struggling with me SQL statement when I do something like this. For some reason, I get a conversion failed when converting the varchar value 'A' to data type int. I am not sure how I should fix this problem.
foreach(var selectedItems in myCheckBoxArray){
if(selectedItems.Checked){
string q = "SELECT * FROM [tb1] as tb1 LEFT JOIN [tb2] as tb2 ON tb1.id = tb2.id
LEFT JOIN [tb3] as tb3 ON tb1.eId = tb3.eId
WHERE employeeName = '" + selectedItems.Text + //get the name
"' AND empFavorityNumber = '" + selectedItems.Text + "'" //get the integer
}
}
NEW EDITED
CheckBox[] myCheckBoxArray = new CheckBox[5];
myCheckBoxArray[0] = checkBoxA;
myCheckBoxArray[1] = checkBoxB;
myCheckBoxArray[2] = checkBoxC;
myCheckBoxArray[3] = checkBoxD;
myCheckBoxArray[4] = checkBoxE;
CheckBox[] mySecCheckBoxArray = new CheckBox[5];
mySecCheckBoxArray[0] = checkBox1;
mySecCheckBoxArray[1] = checkBox2;
mySecCheckBoxArray[2] = checkBox3;
mySecCheckBoxArray[3] = checkBox4;
mySecCheckBoxArray[4] = checkBox5;
foreach(var selectedItems in myCheckBoxArray) {
foreach (var secondselectedItemsin in mySecondCheckBoxArray)
{
if (checkedItems.Checked)
{
string q = "SELECT * FROM [tb1] as tb1 LEFT JOIN [tb2] as tb2 ON tb1.id = tb2.id
LEFT JOIN [tb3] as tb3 ON tb1.eId = tb3.eId
WHERE employeeName = '" + selectedItems.Text + //get the name
"' AND empFavorityNumber = '" + secondselectedItems.Text + "'" //get the integer
}
}
}
Getting SQLException with this "super useful" exception message (Incorrect syntax near ','.) , was wondering if anyone could see anything wrong with the syntax at a glace?
It is code based off of the example that can be found at http://www.jarloo.com/c-bulk-upsert-to-sql-server-tutorial/
private void importToolStripMenuItem_Click(object sender, EventArgs e)
{
DataTable import = new DataTable();
DialogResult result = this.importFileDialog.ShowDialog();
if (DialogResult.OK == result)
{
Stream importStream = this.importFileDialog.OpenFile();
import.ReadXml(importStream);
importStream.Close();
string tmpTable = "select top 0 * into #import from tblJob;";
using (SqlConnection con = new SqlConnection(CONSTRING))
{
con.Open();
SqlCommand cmd = new SqlCommand(tmpTable, con);
cmd.ExecuteNonQuery();
SqlBulkCopyOptions options = SqlBulkCopyOptions.KeepIdentity;
using (SqlBulkCopy bulk = new SqlBulkCopy(con))
{
bulk.DestinationTableName = "#import";
bulk.WriteToServer(import);
}
//http://www.jarloo.com/c-bulk-upsert-to-sql-server-tutorial/
//Now use the merge command to upsert from the temp table to the production table
string mergeSql = "merge into tblJob as Target " +
"using #import as Source " +
"on " +
"Target.[Location]=Source.[Location]," +
"Target.[Schedule]=Source.[Schedule] " +
"when matched then " +
"update set Target.[Complete]=Source.[Complete]," +
"Target.[Cost]=Source.[Cost]," +
"Target.[Description]=Source.[Description]";
//"when not matched then " +
//"insert (Symbol,Price,Timestamp) values (Source.Symbol,Source.Price,Source.Timestamp)" +
//";";
cmd.CommandText = mergeSql;
cmd.ExecuteNonQuery();
//Clean up the temp table
cmd.CommandText = "drop table #import";
cmd.ExecuteNonQuery();
}
dgvJobs.DataSource = getData("select * from tblJob");
If you want to have multiple Join criteria in your MERGE, you need to use the AND keyword (not a comma ,, as you're using now).
Instead of
merge into tblJob as Target
using #import as Source on Target.[Location]=Source.[Location], Target.[Schedule]=Source.[Schedule]
that you're using, use this instead:
MERGE INTO dbo.tblJob AS Target
USING #import AS Source ON Target.[Location] = Source.[Location]
AND Target.[Schedule] = Source.[Schedule]
This is true for any join condition, also for INNER JOIN and LEFT OUTER JOIN or any other join type, too.