Select datatable with join return 0 - c#

I have one DataTable that executes this SQL query on my MS Access database in C#:
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT tblCdDvd.Cod, tblCdDvd.Nome, tblCdDvd.Tamanho, tblTipo.Tipo, tblCdDvd.Grupo FROM [tblCdDvd] INNER JOIN [tblTipo] ON tblCdDvd.Tipo=tblTipo.Cod WHERE Status = TRUE");
If I use
DataRow[] result = dtCdDvd.Select("[Grupo]=0");
the result is 0 rows and exist registry with informed code.
The more interesting is if my SQL query runs
DataTable dtCdDvd = cls.Fun_RetornaDataTable("SELECT Grupo FROM tblCdDvd");
without join table my result is different of 0.
My function of return datatable
public DataTable Fun_RetornaDataTable(string query)
{
DataTable dt = null;
using (var dbcon = new OleDbConnection(Fun_ConnString()))
{
dbcon.Open();
if (dbcon.State == ConnectionState.Open)
{
var command = new OleDbCommand(query, dbcon);
dt = new DataTable();
dt.Load(command.ExecuteReader());
}
}
return dt;
}

Very difficult to understand the question, but a couple of things that stand out.
" WHERE Status = TRUE"
What is 'Status'? Is it defined in one of the tables uniquely?
When you run "SELECT Grupo FROM tblCdDvd", are you getting any rows returned?
"the result is 0 rows and exist registry with informed code"
What does this mean in English?

Related

SQL Query not Retrieving All Rows in C# Application

I have a stored procedure created in my SQL Server 2012 database that selects data from multiple tables. In C#, I use this procedure to show data in a datagridview.
Issue: when I execute the query in SQL Server, I get the correct result which returns 3 rows, but in C#, it returns only 2 rows.
Query:
SELECT DISTINCT
Employee.Employee_No AS 'Badge'
,Employee.Employee_Name_Ar AS 'Emp Name'
,Employee.Basic_Salary AS 'Basic'
,Employee.Current_Salary AS 'Current'
,Attendance.Present
,Attendance.Leave
,Attendance.Othe_Leave AS 'OL'
,Pay_Slip.Salary_Amount AS 'Sal. Amt.'
,(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00)) AS 'O/T Amt.'
,(ISNULL(Pay_Slip.Salary_Amount, 0.00) + ISNULL(ISNULL(Pay_Slip.OverTime1_Amount, 0.00) + ISNULL(Pay_Slip.OverTime2_Amount, 0.00), 0.00)) AS 'Sal. & O/T'
,Pay_Slip.Trasnport AS 'Allow'
,Pay_Slip.CostofLiving AS 'O.Allow'
,Pay_Slip.Gross_Salary AS 'T Salary'
,Pay_Slip.Insurance1_Amount AS 'ss 7%'
,Pay_Slip.Insurance2_Amount AS 'ss 11%'
,(ISNULL(Pay_Slip.Insurance1_Amount, 0.00) + ISNULL(Pay_Slip.Insurance2_Amount, 0.00)) AS 'Total s.s'
,Pay_Slip.Tax
,Pay_Slip.Personal_Loans AS 'Advance'
,Pay_Slip.Other_Deductions AS 'Ded.'
,Pay_Slip.Net_Salary AS 'Net'
FROM Pay_Slip
LEFT JOIN Employee ON Pay_Slip.Employee_No = Employee.Employee_No
LEFT JOIN Attendance ON Pay_Slip.Employee_No = Attendance.Employee_No
WHERE Pay_Slip.Month = '5'
AND Pay_Slip.Year = '2020'
AND Attendance.Month = '5'
AND Attendance.Year = '2020'
Executing this query in SQL Server returns 3 rows which are the employee slips on May-2020 (They all have values in May-2020).
C# code:
private void dateTimePicker_ReportDate_ValueChanged(object sender, EventArgs e)
{
try
{
DateTime date = dateTimePicker_ReportDate.Value;
String Month = dateTimePicker_ReportDate.Value.ToString("MM");
String Year = dateTimePicker_ReportDate.Value.ToString("yyyy");
String str = "server=localhost;database=EasyManagementSystem;User Id=Jaz;Password=Jaz#2020;Integrated Security=True;";
String query = "Execute EMP_PAY_ATT_Selection #Month, #Year";
SqlConnection con = null;
con = new SqlConnection(str);
SqlCommand cmd= new SqlCommand(query, con);
cmd.Parameters.Add("#Month", SqlDbType.Int).Value = Convert.ToInt32(Month);
cmd.Parameters.Add("#Year", SqlDbType.Int).Value = Convert.ToInt32(Year);
SqlDataReader sdr;
con.Open();
sdr = cmd.ExecuteReader();
if (sdr.Read())
{
DataTable dt = new DataTable();
dt.Load(sdr);
dataGridView_Report.DataSource = dt;
dataGridView_Report.EnableHeadersVisualStyles = false;
dataGridView_Report.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
}
else
{
dataGridView_Report.DataSource = null;
dataGridView_Report.Rows.Clear();
}
con.Close();
}
catch (Exception es)
{
MessageBox.Show(es.Message);
}
}
Again, when running this, it only returns 2 rows on the datagridview. While it should be 3 rows.
These are the tables:
The DbDataReader.Read method advances the reader to the next record.
There is no way to rewind a data reader. Any methods that you pass it to will have to use it from whatever record it is currently on.
If you want to pass the reader to DataTable.Load(), do not Read from it yourself. If you merely want to know if it contains records, use HasRows.

SQL IN operator in asp.net C#

I am getting an error while binding a gridview. I want to select multiple records from database using SQL IN operator. Please help me to overcome this problem.
aspx.cs code
string codeId = "4,3,5,7";
int[] result = codeId.Split(',').Select(int.Parse).ToArray();
string Qry = "select CodeId,Code,AccountHead,Rate from AccountHeads Where CodeId IN " + result; //Getting error here
SqlDataAdapter adp = new SqlDataAdapter(Qry, con);
DataTable dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.EmptyDataText = "no records founds";
GridView1.DataBind();
//Hide Gridview columns
GridView1.Columns[0].Visible = false;
}
You don't need to split your string with , and use IEnumerable.Select to select int values.
You already have a nicely formatted string for IN clause. You just need to use your values in () like;
string Qry = string.Format(#"select CodeId,Code,AccountHead,Rate
from AccountHeads Where CodeId IN ({0})",
codeId);

C#: Sort DATATABLE with column date

I know it is a repeated question but i have tried much but i am getting exception
$exception {"String was not recognized as a valid DateTime."} System.Exception {System.FormatException}
Following is my code please check and guide
SQL QUERY
SELECT gangId as gang, respectPoints as respectPoints,DATE_FORMAT( purchasedDate, '%d-%m-%Y') as date_purchase FROM tbl_gang t where gangId=" + gangId
Data Access Layer Code
DataTable dt = new DataTable();
MySqlCommand cmd = conn.CreateCommand();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
cmd.CommandText = inAppPurchaseQuery;
da.Fill(dt)
Sorting Code
dt = gangRPObj.getGangRPLogsBL(gangId, fromDate, toDate);
var sortedTable = dt.AsEnumerable()
.OrderBy(r => DateTime.ParseExact(("date_purchase"),
"dd-mm-yyyy", null))
.CopyToDataTable();
Thanks
You are passing string to datetime conversion that's why exception is coming. Try
var orderedRows = from row in dt.AsEnumerable()
let date = DateTime.ParseExact(row.Field<string>("date_purchase"),"dd-mm-yyyy", null)
orderby date
select row;
Sorting a date-column as string also doesn't sort correctly. You should also sort in the database instead of in memory and use parameters instead of string concatenation to prevent sql-injection and date-conversion-issues like this.
string sql = #"SELECT gangId as gang,
respectPoints as respectPoints,
DATE_FORMAT(purchasedDate, '%d-%m-%Y') as date_purchase,
FROM tbl_gang t
WHERE gangId=#gangId
ORDER BY purchasedDate ASC";
using (var cmd = new MySqlCommand(sql, conn))
using (var da = new MySqlDataAdapter(cmd))
{
da.SelectCommand.Parameters.Add("#gangId", MySql.Data.MySqlClient.MySqlDbType.Int32).Value = gangID;
da.Fill(dt); // no need to order this on client side
}

access 2007 query and c# datatable show different output

I have the below query in access 2007 which gave me correct results using the sql design view of access..
SELECT B1.LAYER_TYPE,
B1.LAYER_NAME AS LAYER_NAME,
B2.LAYER_NAME AS RELATED_LAYER_NAME,
B3.LAYER_NAME AS RELATED_LAYER2_NAME,
C.RULE_NAME
FROM (((NCS_RULES_RELATIONS AS A
LEFT JOIN NCS_LAYERS AS B1 ON A.LAYER_ID = B1.LAYER_ID)
LEFT JOIN NCS_LAYERS AS B2 ON A.RELTD_LAYER_ID = B2.LAYER_ID)
LEFT JOIN NCS_LAYERS AS B3 ON A.RELTD_LAYER2_ID = B3.LAYER_ID)
LEFT JOIN NCS_RULES AS C ON A.RULE_ID = C.RULE_ID
ORDER BY B1.LAYER_TYPE;
the results are below :
but when i try to get the results to a datatable using c# and oledbconnection to access, the RULE_NAME field value for the last row shows weird results(see pic below).
my code for retrieving table is below:
public DataTable GetTable(string strSelectSQL)
{
if (this.con.State != ConnectionState.Open)
con.Open();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
IDbCommand command = con.CreateCommand();
command.CommandText = strSelectSQL;
command.Connection = con;
IDbDataAdapter da = factory.CreateDataAdapter();
da.SelectCommand = command;
da.Fill(ds);
dt = ds.Tables[0];
con.Close();
return dt;
}
can somebody help me with this strange behavior?
Seems everything is fine. My guess you have multiline value in Rule_name field like this: AnnoFromLine\n\rDimOnLine. Datagridview displaying multiline value as you can see and sql design view diplaying just first line.

problem with getting data from database

I am trying to get the data from database by using the below code.....
if there is no data in the table it will always goes to
this statement
I am using mysql.net connector for getting the data and i am doing winforms applications
using c#
public DataTable sales(DateTime startdate, DateTime enddate)
{
const string sql = #"SELECT memberAccTran_Source as Category, sum(memberAccTran_Value) as Value
FROM memberacctrans
WHERE memberAccTran_DateTime BETWEEN #startdate AND #enddate
GROUP BY memberAccTran_Source";
return sqlexecution(startdate, enddate, sql);
}
and the below code is for return sqlexceution...function..
private static DataTable sqlexecution(DateTime startdate, DateTime enddate, string sql)
{
var table = new DataTable();
using (var conn = new MySql.Data.MySqlClient.MySqlConnection(connectionstring))
{
conn.Open();
var cmd = new MySql.Data.MySqlClient.MySqlCommand(sql, conn);
var ds = new DataSet();
var parameter = new MySql.Data.MySqlClient.MySqlParameter("#startdate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter.Direction = ParameterDirection.Input;
parameter.Value = startdate.ToString(dateformat);
cmd.Parameters.Add(parameter);
var parameter2 = new MySql.Data.MySqlClient.MySqlParameter("#enddate", MySql.Data.MySqlClient.MySqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
parameter2.Value = enddate.ToString(dateformat);
cmd.Parameters.Add(parameter2);
var da = new MySql.Data.MySqlClient.MySqlDataAdapter(cmd);
da.Fill(ds);
try
{
table = ds.Tables[0];
}
catch
{
table = null;
}
}
return table;
}
even if there is no data the process flow will goes to this line
table = ds.Tables[0];
how can i reduce this .....
would any one pls help on this....
In your case if you are think that catch block will get excuted if there is no row available than you are wrong because Even if there is no data once select query is get exucuted without exception it Creates datatable with the columns but with no rows.
for this i think you can make use of ds.table[0].rows.count property which return 0 if there is no row in datatable.
if ( ds.Tables[0].Rows.Count > 0 )
table = ds.Tables[0];
else
table=null;
It returns an empty table. This is common behavior. If you want to have table null you should check for the row count :
If ( ds.Tables[0].Rows.Count >. 0 )
table = ds.Tables[0];
Else
table=0
I'm not really sure what you're asking here ... I assume you want it to skip the table = ds.tables[0] line if there is no data?
if thats the case a try/catch wont work as it wont throw an exception ... try something like this instead ...
if(ds.Tables.Count > 0 && ds.Tables[0].Rows.Count >0)
{
table = ds.Tables[0];
}
else
{
table = null;
}

Categories