Executing SQL command works in SQL but not in .C# - c#

I have a quite large SQL query that works as expected when i´m exceuting it in MS SQL. However when I run it from C# it does not fetch any rows (dataTable does not return any rows). If I instead use a simple query, for e.g. "SELECT * Accounts FROM TableX" from C#, dataTable returns all the rows it should do. I also tried to remove all the spaces from the SQL query so everything was on the same line, but without any change. Here is the code:
internal void GetData()
{
try
{
using (SqlConnection connection = new SqlConnection(connectionBuilder.ToString())) //1. Open connection
{
connection.Open();
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(GetSqlString(), connection))
{
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
foreach (DataRow dataRow in dataTable.Rows)
{
var field1 = dataRow[0];
var field2 = dataRow[1];
Logger.Log(field1 + " " + field2);
}
}
}
}
catch (Exception ex)
{
utilityProvider.Log("Error" + ex.ToString());
}
}
private string GetSqlString()
{
return #"SELECT
Field1 = subscr.cind_recipient,
Field2 = COALESCE(
a.name, s.cind_name,
CASE WHEN c.cind_is_protected_identity = 0 THEN c.fullname
ELSE ISNULL(c.cind_protected_firstname, '') + ' ' + ISNULL(c.cind_protected_lastname, '') END ),
Field3 = COALESCE(CASE WHEN c.cind_is_protected_identity <> 1 THEN c.address1_line3
ELSE c.cind_protected_address1_line3 END,
s.cind_postal_line3),
Field4 = COALESCE(CASE WHEN c.cind_is_protected_identity = 0 THEN c.address1_line1
ELSE c.cind_protected_address1_line1 END,
a.address2_line1, s.cind_postal_line1),
Field5 = COALESCE(CASE WHEN c.cind_is_protected_identity = 0 THEN c.address1_line2
ELSE c.cind_protected_address1_line2 END,
a.address2_line2, s.cind_postal_line2),
Field6 = COALESCE(CASE WHEN c.cind_is_protected_identity = 0 THEN mpc1.cind_postalcode
ELSE mpc.cind_postalcode END,
a.address1_postalcode, s.cind_postal_postalcode),
Field7 = COALESCE(CASE WHEN c.cind_is_protected_identity = 0 THEN mpc1.cind_city
ELSE mpc.cind_city END,
a.address1_city, s.cind_postal_city),
Field8 = c.cind_member_number,
Field9 = ISNULL(COALESCE(c.cind_union_section_idname, a.cind_mml_mub_union_section_idname), a1.cind_mml_mub_union_section_idname),
Field10 = CASE WHEN c.cind_is_protected_identity <> 1 THEN c.cind_soc_sec_no
ELSE c.cind_protected_cind_soc_sec_no END,
Field11 = COALESCE(a.cind_organization_no, s.cind_organization_no),
Field12 = c.gendercodename,
Field13 = cind_count,
Field14 = k1.cind_name,
Field15 = k1.cind_number,
Field16 = k2.cind_name,
Field17 = k2.cind_number,
Field18 = 'sam',
Field19 = subscr.villa_free_exname
FROM dbo.Filteredcind_mml_mub_subscription subscr
INNER JOIN Filteredcind_mml_mub_service svc
ON subscr.cind_mml_mub_service_id = svc.cind_mml_mub_serviceid
AND svc.cind_code = 'PE002'
LEFT JOIN Filteredcind_mml_mub_site s
ON subscr.cind_mml_mub_site_id = s.cind_mml_mub_siteid
LEFT JOIN FilteredAccount a
ON subscr.cind_account_id = a.accountid
LEFT JOIN FilteredAccount a1
ON a1.accountid = s.cind_account_id
INNER JOIN FilteredContact c
ON subscr.cind_contact_id = c.contactid
AND c.statecode = 0
LEFT JOIN Filteredcind_mml_mub_postalcity mpc
ON c.cind_protected_cind_postalcity_id = mpc.cind_mml_mub_postalcityid
LEFT JOIN Filteredcind_mml_mub_postalcity mpc1
ON c.cind_postalcity_id = mpc1.cind_mml_mub_postalcityid
LEFT JOIN Filteredcind_mml_mub_county lan
ON c.cind_county_id = lan.cind_mml_mub_countyid
LEFT JOIN Filteredcind_mml_mub_country land
ON lan.cind_country_id = land.cind_mml_mub_countryid
LEFT JOIN (Filteredcind_mml_mub_membership m1
INNER JOIN (SELECT mt1.cind_mml_mub_membership_typeid
FROM Filteredcind_mml_mub_membership_type mt1
WHERE mt1.cind_code = 'PRDI-45') mtt1
ON mtt1.cind_mml_mub_membership_typeid = m1.cind_mml_mub_membership_type_id)
ON c.contactid = m1.cind_contact_id
AND (m1.statuscode = 1
OR m1.statuscode = 434578)
AND m1.statecode = 0
LEFT JOIN Filteredcind_mml_mub_local_union k1
ON m1.cind_mml_mub_local_union_id = k1.cind_mml_mub_local_unionid
LEFT JOIN (Filteredcind_mml_mub_membership m2
INNER JOIN (SELECT mt2.cind_mml_mub_membership_typeid
FROM Filteredcind_mml_mub_membership_type mt2
WHERE mt2.cind_code = 'EXTR-01') mtt2
ON mtt2.cind_mml_mub_membership_typeid = m2.cind_mml_mub_membership_type_id)
ON c.contactid = m2.cind_contact_id
AND (m2.statuscode = 1
OR m2.statuscode = 126670001)
AND m2.statecode = 0
LEFT JOIN Filteredcind_mml_mub_local_union k2
ON m2.cind_mml_mub_local_union_id = k2.cind_mml_mub_local_unionid
WHERE subscr.statuscode = 1
AND subscr.statecode = 0";
}

If SELECT * works then its likely to be a timeout issue. However you should be receiving an exception.
The default timeout is 30 seconds.
How long does it take your query to run in MSSQL?
change the timeout by setting
cmd.Timeout = 300; // Change the number of seconds.
Alternatively improve the efficiency of your query.

Reduce your SQL line by line then you'll find the problem. Start with dropping all column, use * instead (as CathalMF said), then drop the joins, one by one.

Related

Search Function Textbox not working properly c#

My code:
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text == "")
{
DGViewListItems.Rows.Clear();
populateTable();
}
else
{
if (byItemcode.Checked == true)
{
DGViewListItems.Rows.Clear();
using (SqlConnection con = db.Connect())
{
try
{
//these Messageboxes is just for testing. to test if the data is correct
MessageBox.Show('%' + STEntry.whseFr.Text.Trim() + '%');
MessageBox.Show('%' + txtSearch.Text.Trim() + '%');
SqlDataReader rd;
SqlCommand cmd = new SqlCommand("sp_WhseItemsList", db.Connect());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Action", "I");
switch (activeform.formname)
{
case "Issuance List":
//cmd.Parameters.AddWithValue("#WHSE", STEntry.whseFr.Text);
break;
case "Stocks Transfer List":
cmd.Parameters.AddWithValue("#WHSE", STEntry.whseFr.Text.Trim());
break;
case "Stocks Adjustment List":
cmd.Parameters.AddWithValue("#WHSE", SADJEntry.txtWhse.Text.Trim());
break;
}
cmd.Parameters.AddWithValue("#Desc", "");
cmd.Parameters.AddWithValue("#Itemcode", '%' + txtSearch.Text.Trim() + '%');
rd = cmd.ExecuteReader();
int i = 0;
if (rd.HasRows)
{
while (rd.Read())
{
DGViewListItems.Rows.Add();
DGViewListItems.Rows[i].Cells["itemcode"].Value = rd["itemcode"].ToString();
DGViewListItems.Rows[i].Cells["whsecode"].Value = rd["whsecode"].ToString();
DGViewListItems.Rows[i].Cells["description"].Value = rd["description"].ToString();
DGViewListItems.Rows[i].Cells["uom"].Value = rd["uom"].ToString();
DGViewListItems.Rows[i].Cells["quantity"].Value = rd["quantity"].ToString();
i++;
}
}
}
catch (Exception ex)
{
}
}
}
else if (byDescription.Checked == true)
{
}
}
}
This is not working for me, because it does not populate the dgv correctly. I don't think the query is the problem inside the stored procedure, because I tried the query manually and its working fine
The query I tried:
SELECT DISTINCT A.*, B.description, B.uom
FROM inventoryTable A
LEFT OUTER JOIN Items B
ON A.itemcode = B.itemcode WHERE (A.whsecode = 'WHSE1' AND A.itemcode LIKE '%S%');
The output:
And here is the output for the code in the textchanged event:
Here is more example output:
This is the stored procedure content for reference:
ALTER PROCEDURE [dbo].[sp_WhseItemsList]
#Action char(5) = '',
#WHSE char(15) = '',
#Desc varchar(50) = '',
#Itemcode char(15) = ''
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
IF #Action = 'A'
BEGIN
SELECT DISTINCT A.*, B.description, B.uom
FROM inventoryTable A
LEFT OUTER JOIN Items B
ON A.itemcode = B.itemcode WHERE A.whsecode = #WHSE;
END
IF #Action = 'I'
BEGIN
SELECT DISTINCT A.*, B.description, B.uom
FROM inventoryTable A
LEFT OUTER JOIN Items B
ON A.itemcode = B.itemcode WHERE (A.whsecode = #WHSE) AND (A.itemcode LIKE #Itemcode);
END
IF #Action = 'D'
BEGIN
SELECT DISTINCT A.*, B.description, B.uom
FROM inventoryTable A
LEFT OUTER JOIN Items B
ON A.itemcode = B.itemcode WHERE (A.whsecode = #WHSE) AND (B.description LIKE #Desc);
END
END
Your #Itemcode is a char(15), which means it always has 15 positions. So this becomes:
A.itemcode LIKE '%S% ').
And LIKE does not ignore trailing spaces, like an = would do. So it only matches a value that contains "S" and ends in 12 spaces.

Display records in database that uses a join with where clause in datagridview

What I am trying to do here is:
Display ALL Employees (in the datagridview)
Display Employees that HAVE health insurance records (in the datagridview)
Display Employees WITHOUT health insurance records(in the datagridview)
I can now display all of my employees to the datagridview(dgvEmp) with this stored procedure:
IF #action_type = 'DisplayAllEmployees'
BEGIN
SELECT e.employee_id, e.employee_name, e.city, e.department, e.gender,
h.health_insurance_provider, h.plan_name, h.monthly_fee, h.insurance_start_date
FROM dbo.Employee e
LEFT JOIN dbo.EmployeeHealthInsuranace h ON h.employee_id = e.employee_id
END
and this function (in my winforms):
private void FetchEmpDetails( string readType ) {
//Load/Read Data from database
using ( SqlConnection con = new SqlConnection( connectionStringConfig ) )
using ( SqlCommand sqlCmd = new SqlCommand( "spCRUD_Operations", con ) ) {
try {
con.Open();
DataTable dt = new DataTable();
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue( "#action_type", readType );
sqlCmd.Connection = con;
SqlDataAdapter sqlSda = new SqlDataAdapter( sqlCmd );
sqlSda.Fill( dt );
dgvEmp.AutoGenerateColumns = false;//if true displays all the records in the database
dgvEmp.Columns[ 0 ].DataPropertyName = "employee_id";
dgvEmp.Columns[ 1 ].DataPropertyName = "employee_name";
dgvEmp.Columns[ 2 ].DataPropertyName = "city";
dgvEmp.Columns[ 3 ].DataPropertyName = "department";
dgvEmp.Columns[ 4 ].DataPropertyName = "gender";
dgvEmp.Columns[ 5 ].DataPropertyName = "health_insurance_provider";
dgvEmp.Columns[ 6 ].DataPropertyName = "plan_name";
dgvEmp.Columns[ 7 ].DataPropertyName = "monthly_fee";
dgvEmp.Columns[ 8 ].DataPropertyName = "insurance_start_date";
dgvEmp.Columns[ 8 ].DefaultCellStyle.Format = "MMMM dd, yyyy";
dgvEmp.DataSource = dt;
} catch ( Exception ex ) {
MessageBox.Show( "Error: " + ex.Message );
}
}
}
I can display all by calling the function: FetchEmpDetails( "DisplayAllEmployees" );
But, when I try to display Employees that HAVE health insurance records or display Employees WITHOUT health insurance records (with the function call through winforms), I can't get them to display at the dataGridView. THE DATA GRID VIEW IS JUST BLANK.
This is the Stored Procedure:
ELSE IF #action_type = 'WithHealthInsuranceRecords'
BEGIN
SELECT e.employee_id, e.employee_name, e.city, e.department, e.gender,
h.health_insurance_provider, h.plan_name, h.monthly_fee, h.insurance_start_date
FROM dbo.Employee e
INNER JOIN dbo.EmployeeHealthInsuranace h ON h.employee_id = e.employee_id
WHERE h.monthly_fee > 0
END
ELSE IF #action_type = 'WithoutHealthInsuranceRecords'
BEGIN
SELECT e.employee_id, e.employee_name, e.city, e.department, e.gender,
h.health_insurance_provider, h.plan_name, h.monthly_fee, h.insurance_start_date
FROM dbo.Employee e
LEFT JOIN dbo.EmployeeHealthInsuranace h ON h.employee_id = e.employee_id
WHERE h.monthly_fee = 0
END
But, If I run this as "New Query" in my server explorer, the expected output shows up:
EDIT: Thanks to everyone who commented and posted an answer, those are very helpful and I appreciate it.
When I was taking a break I found the problem, my action_type parameter was #action_type NVARCHAR(25), then I realized that the string that I passed there was > 25. I now changed it to #action_type NVARCHAR(100) and it now displays well!
Your query is wrong:
WHERE h.monthly_fee = 0
This will filter the table to rows that are not null, which basically means you are doing an INNER JOIN not a LEFT.
Instead, you can either change it to:
WHERE h.monthly_fee IS NULL;
Or better, use a NOT EXISTS query:
SELECT e.employee_id, e.employee_name, e.city, e.department, e.gender,
h.health_insurance_provider, h.plan_name, h.monthly_fee, h.insurance_start_date
FROM dbo.Employee e
WHERE NOT EXISTS (SELECT 1
FROM dbo.EmployeeHealthInsuranace h
WHERE h.employee_id = e.employee_id);

Is possible to combine SIMPLE values and MULTIVALUEs in conditions when you are doing a SELECT on UniVerse Database with UNNEST

From Universe prompt I run my command
> SELECT SUM(MONTREMB),SUM(MONTCAP),SUM(MONTINT) FROM UNNEST TAVANCE.001 ON AVA_ASS WHERE ETAT =1 AND MAXDTEREMB >= '2019-01-01' AND MAXDTEREMB <= '2019-02-15' AND MONTREMB = 0;
And I get totals
SUM ( MONTREMB ) SUM ( MONTCAP ) SUM ( MONTINT )
0 -599300 2144637
This is my table DICT TAVANCE.001
Field......... Field. Field........ Conversion.. Column......... Output Depth &
Name.......... Number Definition... Code........ Heading........ Format Assoc..
#ID D 0 TAVANCE.001 10L S
KEYCREDIT D 0 KEYCREDIT 15L S
ETAT D 1 ETAT 1R S
MATRICULE D 2 MATRICULE 12L S
MONTANT D 3 MONTANT 12R S
INTERET D 4 INTERET 2R S
DUREE D 6 DUREE 2R S
DTEAVANCE D 7 D/E DTEAVANCE 10L S
MENSUALITE D 9 MENSUALITE 12R S
DTEREMB D 10 D/E DTEREMB 10L M AVA_A
SS
PERIORMBT D 10 PERIORMBT 20R S
MONTREMB D 11 MONTREMB 12R M AVA_A
SS
MONTINT D 12 MONTINT 12R M AVA_A
SS
MONTCAP D 14 MONTCAP 12R M AVA_A
I.NOM I TRANS(TSIGNAG I.NOM 40L S
PE.031,MATRIC
ULE,NOM,'X')
AVA_ASS PH DTEREMB
MONTREMB
#SELECT PH MATRICULE
I.NOM MONTANT
RBTCAP
DTEAVANCE
ETAT PMT
#EMPTY.NULL X
25 records listed.
In the condition of my select command, ETAT and MAXDTEREMB are simple value but MONTREMB is multivalue
The problem is that in my c# problem with the same SELECT command
if (checkInteret.Checked == true)
sRequete = "SELECT SUM(MONTREMB),SUM(MONTCAP),SUM(MONTINT) FROM UNNEST " + tableGroupe + " ON AVA_ASS WHERE (ETAT <> 1 AND ETAT <> 2) AND DTEREMB <= '" + sDateFin + "' AND MONTREMB = 0 ";
U2DataAdapter da = new U2DataAdapter(sRequete, con);
DataSet ds = new DataSet();
da.Fill(ds, "TAVANCE");
con.Close();
con.Open();
tAvance = null;
tAvance = ds.Tables["TAVANCE"];
With tavance.rows.count, not result is displayed. Is there an error in my SELECT command.
For more details, I'm using U2toolkit for .Net to connect to Universe database
using U2.Data.Client;
U2Connection con = new U2Connection();
UniSession session = null;
U2ConnectionStringBuilder conn_str = new U2ConnectionStringBuilder();
string UserId = "root";
string PassWord = "xxxxxx";
string server = "192.xxxxx";
string Database = "LACCOUNT";
string ServerType = "UNIVERSE";
conn_str.UserID = UserId;
conn_str.Password = PassWord;
conn_str.Server = server;
conn_str.Database = Database;
conn_str.FirstNormalForm = false;
conn_str.ExpandMultiValueRows = true;
conn_str.ServerType = ServerType;
conn_str.Connect_Timeout = 1200;
con.ConnectionString = conn_str.ToString();
con.Open();

SQL Server : WHERE argument

I have a SQL statement where I want to filter out the year and the place. The problem is that when I type a year, all the data for this year is being displayed, which is fine but when I input the place it lists places from another year too.
I know that it is so because of the or but what do I have to write instead to get my desired result?
adapter = new SqlDataAdapter
(#"select a.FALL, m.CODE, m.ANZ, m.TDAT
from lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid
where year(m.TDAT) = #jahr or m.Einrichtung= #einricht
order by a.FALL",
"Server = sds; Database = dds;Trusted_Connection = True");
EDIT:
SqlDataAdapter adapter;
adapter = new SqlDataAdapter("select a.ISH_FALLZAHL, m.ML_CODE, m.ML_ANZ, m.ML_LSTDAT From lst_mdmel_lis_tab m with (nolock) inner join lst_absae_tab a with (nolock) on a.aid = m.aid where (#jahr IS NULL OR YEAR(m.ML_LSTDAT) = #jahr) and (#einricht IS NULL OR m.L_ANSTALT = #einricht) order by a.ISH_FALLZAHL", "Server = igvproli19; Database = ADM;Trusted_Connection = True");
adapter.SelectCommand.Parameters.AddWithValue("#jahr", textBox1.Text);
adapter.SelectCommand.Parameters.AddWithValue("#einricht", textBox2.Text);
ds = new DataTable(" ");
adapter.Fill(ds);
dataGridView1.DataSource = ds;
where
(#jahr IS NULL OR YEAR(m.TDAT) = #jahr)
and (#einricht IS NULL OR m.Einrichtung = #einricht)
Change these two lines:
adapter.SelectCommand.Parameters.AddWithValue("#jahr", textBox1.Text);
adapter.SelectCommand.Parameters.AddWithValue("#einricht", textBox2.Text);
to:
if (textBox1.Text == null || textBox1.Text == "")
{
adapter.SelectCommand.Parameters.AddWithValue("#jahr", DBNull.Value);
}
else
{
adapter.SelectCommand.Parameters.AddWithValue("#jahr", textBox1.Text);
}
if (textBox2.Text == null || textBox2.Text == "")
{
adapter.SelectCommand.Parameters.AddWithValue("#einricht", DBNull.Value);
}
else
{
adapter.SelectCommand.Parameters.AddWithValue("#einricht", textBox2.Text);
}
Assuming both arguments are provided, you can write as following:
adapter = new SqlDataAdapter
("select a.FALL, m.CODE, m.ANZ, m.TDAT From lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid
where year(m.TDAT) = #jahr or (m.Einrichtung= #einricht and year(m.TDAT)=#jahr)
order by a.FALL", "Server = sds; Database = dds;Trusted_Connection = True");
To search by more than one filter you have to use AND instead of OR but to filter by year if no place is provided I think something like this should work:
where (year(m.TDAT) = #jahr AND m.Einrichtung= #einricht) OR
(year(m.TDAT) = #jahr AND #einricht IS NULL) OR
(#jahr IS NULL AND m.Einrichtung= #einricht)
If you might have place, year or both, then the best way would be to have 3 separate where clauses for each of those cases, f. e.
var year = ""; // Set value.
var place = ""; // Set value.
var whereClause = "where " + year != null && place != null ?
"year(m.TDAT) = #jahr AND m.Einrichtung = #einricht" : year != null ?
"year(m.TDAT) = #jahr" :
"m.Einrichtung = #einricht";
adapter = new SqlDataAdapter(
"select a.FALL, m.CODE, m.ANZ, m.TDAT From lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid " + whereClause +
" order by a.FALL", "Server = sds; Database = dds;Trusted_Connection = True");
Also, depending on whether you want to accept empty strings or not you can change != null comparison with string.IsNullOrEmpty or string.IsNullOrWhiteSpace methods.
You should use AND rather than OR. By using AND means that it will show the results which have the YEAR and PLACE the same with your parameter. If you are using OR, it means that it will show you the results that having the year OR the place the same with your parameter.
adapter = new SqlDataAdapter
("select a.FALL, m.CODE, m.ANZ, m.TDAT From lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid
where year(m.TDAT) = #jahr AND m.Einrichtung= #einricht
order by a.FALL", "Server = sds; Database = dds;Trusted_Connection = True");
EDIT
If you are not sure which parameter is given, you could check whether that parameter is null or not, then proceed with the sql.
for example
public void ReadDataFromDB(string Year, string Place)
{
string sql = #"select a.FALL, m.CODE, m.ANZ, m.TDAT From lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid
where 1=1 ";
if (Year != null && Year.Length > 0)
{
sql += "AND year(m.TDAT) = #jahr ";
}
if (Place != null && Place.Length > 0)
{
sql += "AND m.Einrichtung= #einricht ";
}
sql += "order by a.FALL";
adapter = new SqlDataAdapter(sql, "Server = sds; Database = dds;Trusted_Connection = True");
}
If you are afraid of SQL injection detection system like #Dovydas Sopa said, then you have to check it 1 by 1 then decide which Where clause should be put.
public void ReadDataFromDB(string Year, string Place)
{
string sql = #"select a.FALL, m.CODE, m.ANZ, m.TDAT From lst_test m with (nolock)
inner join test2 a with (nolock) on a.aid = m.aid ";
if (Year != null && Place != null)
{
sql += "Where year(m.TDAT) = #jahr AND m.Einrichtung= #einricht ";
}
else if (Year != null && Place == null)
{
sql += "Where year(m.TDAT) = #jahr ";
}
else if (Place != null && Year == null)
{
sql += "Where m.Einrichtung= #einricht ";
}
sql += "order by a.FALL";
adapter = new SqlDataAdapter(sql, "Server = sds; Database = dds;Trusted_Connection = True");
}

SQL Query within nested for loops in C# windows forms application taking too long to execute

I am working on a Windows Forms C# Application in which I have a method which has nested for loop that is used to retrieve data from an SQL Table with different parameters (trademonth and paymentmonth that are passed from the row and column headers of a DataGridView and the function also stores the data retrieved from the table into the DataGridView.
As I have around 36 rows (trademonths) and 31 columns (paymentmonths), So the for loops run the same query with different parameters for 36*31 times.
I have the following lines of code in the function
public void CalculatePoolPayments(DataGridView datagridpool, string poolpayments, string poolpaymentadjustments)
{
sqlcon = GetConnectionString();
try
{
sqlcon.Open();
for (int i = 0; i < datagridpool.RowCount; i++)
{
int trademonth = Convert.ToInt32(datagridpool.Rows[i].HeaderCell.Value);
for (int j = 0; j < datagridpool.ColumnCount; j++)
{
int paymentmonth = Convert.ToInt32(datagridpool.Columns[j].HeaderCell.Value);
SqlCommand poolpaymentscmd = new SqlCommand(poolpayments, sqlcon);
poolpaymentscmd.Parameters.AddWithValue("#trademonth", trademonth);
poolpaymentscmd.Parameters.AddWithValue("#paymentmonth", paymentmonth);
DataTable dtExpectedAmount = new DataTable();
SqlDataAdapter daExpectedAmount = new SqlDataAdapter();
daExpectedAmount.SelectCommand = poolpaymentscmd;
daExpectedAmount.Fill(dtExpectedAmount);
SqlCommand poolpaymentsadjustmentcmd = new SqlCommand(poolpaymentadjustments, sqlcon);
poolpaymentsadjustmentcmd.Parameters.AddWithValue("#trademonth", trademonth);
poolpaymentsadjustmentcmd.Parameters.AddWithValue("#paymentmonth", paymentmonth);
DataTable dtAdjustment = new DataTable();
SqlDataAdapter daAdjustment = new SqlDataAdapter();
daAdjustment.SelectCommand = poolpaymentsadjustmentcmd;
daAdjustment.Fill(dtAdjustment);
if (dtExpectedAmount.Rows[0][0].ToString() != "")
{
datagridpool.Rows[i].Cells[j].Value = dtExpectedAmount.Rows[0][0].ToString();
if (dtAdjustment.Rows[0][0].ToString() != "")
{
datagridpool.Rows[i].Cells[j].Value = (Convert.ToDouble(dtAdjustment.Rows[0][0].ToString()) + Convert.ToDouble(dtExpectedAmount.Rows[0][0].ToString())).ToString();
}
}
else
datagridpool.Rows[i].Cells[j].Value = 0;
if (dtExpectedAmount.Rows[0][0].ToString() == "" && dtAdjustment.Rows[0][0].ToString() != "")
{
datagridpool.Rows[i].Cells[j].Value = dtAdjustment.Rows[0][0].ToString();
}
// MessageBox.Show(datagridpool.Rows[0].Cells[9].Value.ToString());
}
}
sqlcon.Close();
}
catch (SqlException se)
{
MessageBox.Show(se.Message);
sqlcon.Close();
}
}
SQL Queries
string poolpayments = #"SELECT SUM(a.ExpectedAmt) AS Payment
FROM PaymentReceivable AS a WITH (nolock) LEFT OUTER JOIN
Confirmations AS b WITH (nolock) ON a.ConfirmationID = b.ID LEFT OUTER JOIN
Users AS c WITH (nolock) ON b.BuyBroker = c.ID LEFT OUTER JOIN
Users AS d WITH (nolock) ON b.SellBroker = d.ID
WHERE (a.TradeDateMonth = #trademonth) AND (a.Payment = 'True') AND (a.PaymentDateMonth = #paymentmonth) AND (Adjustment=0 OR Adjustment IS NULL)";
string poolpaymentadjustments = #"SELECT SUM(a.Adjustment) AS Payment
FROM PaymentReceivable AS a WITH (nolock) LEFT OUTER JOIN
Confirmations AS b WITH (nolock) ON a.ConfirmationID = b.ID LEFT OUTER JOIN
Users AS c WITH (nolock) ON b.BuyBroker = c.ID LEFT OUTER JOIN
Users AS d WITH (nolock) ON b.SellBroker = d.ID
WHERE (a.TradeDateMonth = #trademonth) AND (a.Payment = 'True') AND (a.PaymentDateMonth = #paymentmonth) AND (Adjustment!=0 OR Adjustment IS NOT NULL)";
As you can see from the above code I am running two different queries poolpaymentscmd and poolpaymentsadjustmentcmd with parameters trademonth and paymentmonth.
The function is taking around 90 seconds to execute and I am using the same function two times as required by my application. So, the single function is taking up to 180 seconds which I feel is too high for the application.
Is there any better way I can reduce the execution time

Categories