how to get only first row of datatable with modified specific row value - sql

I have query to just summary of total no of jobs running. now I just want some specific result if there is unique rows found like unique category id with assign job then ok with multiple record set. but no category found if is null then just only pass first record from datatable with modified text with 'ALL' as category name. can we achieve this result.
here is my query and some operations I'm doing with them.
string str = "";
DataTable dt = new DataTable();
str = "SELECT j.[JobID], p.[Id] As PreparedEmailID,p.[Title] AS 'PreparedEmailName',j.[CreatedOn],j.[CompletedOn],j.CategoryID,j.[SubscriberCount],j.[EmailsSent],c.[CategoryName] As SubscriberCategory,(SELECT TOP 1 [Message] FROM [LoggedMessages] WHERE [JobID] =j.[JobID] ORDER BY [LoggedMessageID] DESC) AS 'LoggedMessage',(SELECT [Name] FROM tbl_User_master u WHERE u.Id =j.UserID) As CreatedBy FROM [Jobs] AS j INNER JOIN [tbl_Email_master] AS p ON p.[Id] = j.[PreparedEmailID] INNER JOIN [tbl_User_master] AS u ON u.[Id]=j.[UserID] INNER JOIN tbl_Categories c ON c.Id = j.CategoryID OR (c.Id IS NOT NULL AND j.CategoryID IS NULL) where 1=1 ";
if (chk_date.Checked == true)
{
str += " and ( [CreatedOn] between '" + CommonLogic.Get_Date_From_String(txt_date_from.Text, 1);
str += "' and '" + CommonLogic.Get_Date_From_String(txt_date_to.Text, 2) + "' )";
}
if (string.IsNullOrEmpty(txttitle.Text.Trim()))
{
str += string.Empty;
}
else
{
str += " and p.Title like '%" + txttitle.Text.Trim() + "%'";
}
if (ddl_fromuser.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.FromuserID = CONVERT(INT," + Convert.ToInt32(ddl_fromuser.SelectedValue.ToString()) + ")";
}
if (ddl_subcategories.SelectedItem.Text.ToString() == ".All")
{
str += string.Empty;
}
else
{
str += " and j.CategoryID = CONVERT(INT," + Convert.ToInt32(ddl_subcategories.SelectedValue.ToString()) + ")";
}
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().FirstOrDefault();
egrd.DataSource = topRows;
egrd.DataBind();
}
else
{
egrd.DataSource = dt;
egrd.DataBind();
}
ViewState["data"] = dt;
how ever this gives me error like no JobID found to this record set. whether it is still exists in record set.
please help me...
well I tried this solution but no success...……..
if (dt.Rows.Count > 1)
{
dt.Rows[0]["SubscriberCategory"] = "ALL";
var topRows = dt.AsEnumerable().GroupBy(j => j.Field<int>("JobID")).Select(j => j.First()).ToList();
egrd.DataSource = topRows;
egrd.DataBind();
}
it's gives me exception like DataBinding: 'System.Data.DataRow' does not contain a property with the name 'JobID'.

Just replace .ToList() with .CopyToDataTable() resolve my problem

Related

How to run SQL query concurrently in one by one

I am developing one page like Daily SMS Log for retrieving info regarding SMS run in background. I have this SQL code:
First Section
--SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,
-- p.MobileNo,
-- p.Message,
-- p.CharCount,
-- p.strSenderID as Sender,
-- u.strUserName as UserId,
-- ds.strDR as DeliveryStatus,
-- ds.strDiscription as Original_DRStatus,
-- m.strMessageType as MessageType,
-- CONVERT(varchar(20) , p.ReceiveTime) as ReceiveTime,
-- CONVERT(varchar(20) , p.SendTime) as SendTime,
-- CONVERT(varchar(20) , p.DoneTime) as DoneTime,
-- p.RootId as Root,
-- sp.ProviderName,
-- (CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType
-- INTO #Results3
-- FROM NEWSMSLOG_2019_01..LOG_010119 p
-- INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid
-- left join senderids b on b.id = p.senderid
-- left join messagetype m on m.intcode = p.messagetype
-- left join smppproviders sp on sp.RootId=p.RootId
-- where 1=1
Second Section
-- SELECT *
-- FROM #Results3
-- SELECT
-- CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,
-- Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType
-- FROM #Results3
-- WHERE RowNumber BETWEEN('1' -1) * '109299' + 1 AND((('1' -1) * '109299' + 1) + '109299') - 1
Here when I uncomment the first line to where 1=1 then rows retrieved with success. And after that commenting up those line I uncomment second section then result shows bunch of rows. Now it's works fine in Management Studio.
Now I just want this result to grid view and here is my code:
protected void Get_Data()
{
try
{
string str = "";
DataTable dt = new DataTable();
str = "SELECT ROW_NUMBER() OVER (ORDER BY RowId DESC)AS RowNumber,p.CampaignName,";
str += "p.MobileNo,";
str += "p.Message,";
str += "p.CharCount,";
str += "p.strSenderID as Sender,";
str += "u.strUserName as UserId,";
str += "ds.strDR as DeliveryStatus,";
str += "ds.strDiscription as Original_DRStatus,";
str += "m.strMessageType as MessageType,";
str += "CONVERT(varchar(20), p.ReceiveTime) as ReceiveTime,";
str += "CONVERT(varchar(20), p.SendTime) as SendTime,";
str += "CONVERT(varchar(20), p.DoneTime) as DoneTime,";
str += "p.RootId as Root,";
str += "sp.ProviderName,";
str += "(CASE intAccountType WHEN 1 THEN 'Promotional' WHEN 2 THEN 'Transactional' WHEN 3 THEN 'OptIn' END) as AccountType";
str += " INTO #Results3 ";
str += " FROM NEWSMSLOG_2019_01..LOG_010119 p ";
str += " INNER JOIN deliverstatus ds ON p.DeliveryStatus = ds.intDR_status inner join users u on u.id = p.userid";
str += " left join senderids b on b.id = p.senderid";
str += " left join messagetype m on m.intcode = p.messagetype";
str += " left join smppproviders sp on sp.RootId = p.RootId";
str += " where 1 = 1 ";
if(ddl_users.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.userid = ' + CONVERT(varchar(5),"+ Convert.ToInt32(ddl_users.SelectedValue.ToString())+") + '";
}
if (ddl_sender.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.Senderid = '+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+'";
}
if(!string.IsNullOrEmpty(txt_mobileno.Text.Trim()))
{
str += " and p.MobileNo like '' % '"+txt_mobileno.Text.Trim()+"' % ''";
}
else
{
str += string.Empty;
}
if(ddl_delevery.SelectedItem.Text.ToString() =="All")
{
str += string.Empty;
}
else
{
str += " and p.Deliverystatus in ('+CONVERT(varchar(10),"+Convert.ToInt32(ddl_sender.SelectedValue.ToString())+")+')'";
}
if(!string.IsNullOrEmpty(txt_CompaignName.Text.Trim()))
{
str += " and p.CampaignName like ''%'"+txt_CompaignName.Text.Trim()+"'%'' '";
}
else
{
str += string.Empty;
}
if(ddl_account.SelectedItem.Text.ToString() == "All")
{
str += string.Empty;
}
else
{
str += " and p.accounttype = '+CONVERT(varchar(2),"+Convert.ToInt32(ddl_account.SelectedValue.ToString())+")+'";
}
obj.Execute_Query(str);
string str1 = " SELECT * FROM #Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName,AccountType";
str1 += " FROM #Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500' + 1) + '500') - 1";
str1 += " DROP TABLE #Results3";
dt = obj.Get_Data_Table_From_Str(str1);
ViewState["data"] = dt;
egrd.DataSource = dt;
egrd.DataBind();
ViewState["data"] = dt;
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
}
}
But I have no records found in grid view. What's problem is that?
--------------------------Updated--------------------------------------------
namespace BulkSMSSystem.App_Code.DAL
{
public class DAL_General : DataAccess
{
public DataTable Get_Data_Table_From_Str(string str, string cnn_type = "NEWBULKSMS")
{
DataTable dt = new DataTable();
GetConnection(cnn_type);
dt = GetDataTableByQuery(str);
return dt;
}
public void Execute_Query(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
GetExecuteNonQueryByStr(str);
}
public object Execute_Scalar(string str, string cnn_type = "NEWBULKSMS")
{
GetConnection(cnn_type);
object rtn = GetScalarOfStr(str);
return rtn;
}
---------------------------Updated 2-------------------------------------
public DataTable GetDataTableByQuery(string str_query)
{
try
{
mobj_SqlCommand.CommandText = str_query;
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.Text;
//mobj_SqlConnection.Open();
SqlDataAdapter adpt = new SqlDataAdapter(mobj_SqlCommand);
DataTable ds = new DataTable();
adpt.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseConnection();
}
}
public void GetExecuteNonQueryByStr(string query_str)
{
try
{
mobj_SqlCommand.CommandType = CommandType.Text;
mobj_SqlCommand.CommandText = query_str;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
CloseConnection();
}
}
--------------------------Updated 3-----------------------------------
protected void GetConnection(string cnn_db = "NEWBULKSMS")
{
try
{
string Cnn_Str = "";
string ServerName = "SHREE-PC";
string DBUserName = string.Empty;
string DBPassword = string.Empty;
DBPassword += "c#" + Convert.ToChar(49);
string Database = cnn_db;
Cnn_Str = "Data Source=" + ServerName + "; UID=" + DBUserName + "; PWD=" + DBPassword + "; Database=" + Database+";Integrated Security = True";
//Cnn_Str = "Data Source=SHREE-PC;Initial Catalog=Project_DB_MNG;Integrated Security=True";
mstr_ConnectionString = Cnn_Str;
mobj_SqlConnection = new SqlConnection(mstr_ConnectionString);
mobj_SqlCommand = new SqlCommand();
mobj_SqlCommand.CommandTimeout = mint_CommandTimeout;
mobj_SqlCommand.CommandType = CommandType.StoredProcedure;
mobj_SqlCommand.Connection = mobj_SqlConnection;
mobj_SqlConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Error initializing data class." + Environment.NewLine + ex.Message);
}
}
--------------------------Upadted 4--------------------------------------
As you are using temp table with one # sign it means that a temporary table will exists only during your session. However, if you create a temporary table with ##, then every user will be able to use that one, and none other can create a temp table with the same name, but it will be deleted when the owner session expired or disconnect.
So try to use in your code:
...
str += " INTO ##Results3 ";
...
And:
string str1 = " SELECT * FROM ##Results3";
str1 += " SELECT";
str1 += " CampaignName,MobileNo,Message,CharCount,Sender,UserId,DeliveryStatus,";
str1 += "Original_DRStatus,MessageType,ReceiveTime,SendTime,DoneTime,Root,ProviderName
,AccountType";
str1 += " FROM ##Results3";
str1 += " WHERE RowNumber BETWEEN('1' - 1) * '500' + 1 AND((('1' - 1) * '500'
+ 1) + '500') - 1";
str1 += " DROP TABLE ##Results3";

How to avoid every time initialization when value have greater than 0

I have a method that inserts a new record after checking whether it already exists or not.
Here is my method:
protected void btn_save_Click(object sender, EventArgs e)
{
string MobileNo = "";
string replaceValue = txt_mobile.Text.Replace(Environment.NewLine, "$");
string[] values = replaceValue.Split('$');
int uCnt = 0;
int sCnt = 0;
foreach (string item in values)
{
SaveRecord(item.Trim(),out MobileNo,out uCnt,out sCnt);
}
txt_mobile.Text = string.Empty;
if(uCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('Mobile No(s) : "+MobileNo.TrimEnd(',')+" Already Exist');", true);
}
if(sCnt > 0)
{
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + sCnt + " Record(s) Inserted Successfully');", true);
}
Get_Data();
}
public void SaveRecord(string value, out string MobileNo, out int uCnt, out int sCnt)
{
uCnt = 0; //every time initialized to 0
sCnt = 0; //every time initialized to 0
MobileNo = "";
try
{
DataTable dt = new DataTable();
var dot = Regex.Match(value, #"\+?[0-9]{10}");
if (dot.Success)
{
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
dt = obj.Get_Data_Table_From_Str(str);
if (dt.Rows.Count > 0)
{
uCnt++;
MobileNo += value + ",";
}
else
{
string str1 = "INSERT INTO [dbo].[whitelistdata]([UserID],[SenderId],[KeywordID],[MobileNo])";
str1 += "VALUES (" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "," + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + ",1," + value + ")";
obj.Execute_Query(str1);
sCnt++;
}
}
}
catch (Exception ex)
{
CommonLogic.SendMailOnError(ex);
ClientScript.RegisterStartupScript(this.GetType(), "BulkSMS System", "alert('" + ex.Message.ToString() + "');", true);
}
}
The problem is every time it's set to 0 when method has been called I want to prevent them when previous value is greater than 0.
Please help me guys..
Please first identify which combination check-in database.
if UserID AND SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if check the only UserID Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" +
Convert.ToInt32(ddl_users.SelectedValue.ToString()) +"'";
if UserID OR SenderId combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' OR [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "'";
if UserID AND SenderId AND MobileNo combination Match Then
string str = "SELECT TOP 1 [ID],[MobileNo] FROM[dbo].[whitelistdata]";
str += " WHERE [UserID] = '" + Convert.ToInt32(ddl_users.SelectedValue.ToString()) + "' AND [SenderId] = '" + Convert.ToInt32(ddl_senders.SelectedValue.ToString()) + "' AND [MobileNo] = '" + value + "'";
You need to use ref rather than out if you want to keep this design1. That means that the method can assume that the variables are already initialised and you're not forced to re-initialise them within the method:
public void SaveRecord(string value,out string MobileNo,ref int uCnt,ref int sCnt)
{
//uCnt = 0; //initialized by caller
//sCnt = 0; //initialized by caller
MobileNo = ""; //?
....
And at the call site:
SaveRecord(item.Trim(),out MobileNo,ref uCnt,ref sCnt);
You'll also want to do something about MobileNo too if you expect that to accumulate values rather than be over-written each time through the loop. Maybe make it a StringBuilder instead that you just pass normally (no ref or out) and let the SaveRecord method append to. out is definitely wrong for it.
1Many people would frown at a method that clearly wants to return values being declared void and making all returns via ref/out.
Something like:
public bool SaveRecord(string value)
{
...
Returning true for a new record, false for an existing record. I'd probably take out the exception handling from there and let the exception propagate higher before it's handled. Then the call site would be:
if(SaveRecord(item.Trim()))
{
sCnt++;
}
else
{
uCnt++;
MobileNo += item.Trim + ","
}

How to check the record in database exist or not if exist add to jtextarea else left blank (netbean)

Below is my code, which isn't working.
if can please provide example code or edit my code, TY
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/timetable", "root", "");
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 8 ";
pst = con.prepareStatement(sql);
pst = con.prepareStatement(sql1);
rs = pst.executeQuery();
if (rs.next()) {
String sC = rs.getString("subjectcode");
String sN = rs.getString("subjectname");
String Ln = rs.getString("lecturer");
monday8to10.setText(sC + newline + "" + sN + newline + "" + Ln);
} else {
monday8to10.setText("");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/timetable", "root", "");
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 10 ";
pst = con.prepareStatement(sql1);
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while (rs.next()) {
String sC = rs.getString("subjectcode");
String sN = rs.getString("subjectname");
String Ln = rs.getString("lecturer");
monday10to12.setText(sC + newline + "" + sN + newline + "" + Ln);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
I believe to start, pst.executeQuery() requires an argument. You are currently no executing a query at all?
pst.executeQuery(sql1);
Seconds, you need to execute 1 query at a time:
String sql1 = "select * from tt where day like '%monday%'";
String sql = "select * from tt where time = 10 ";
becomes
String sql1 = "select * from tt where time = 10 and day like '%monday%'";
For example, I was just looking back at some of my old DB code.
query = "SELECT m.title, m.year_, m.rt_picture, m.imdb_picture, m.movie_id, u.user_score, u.user_id FROM movie_navigator.movies m, movie_navigator.userratings u WHERE m.movie_id=u.movie_id AND u.movie_id=" + movieId + " LIMIT " + queryPageSize + " OFFSET " + (queryPageSize*pageNumber) + ";";
try{
stmt = conn.createStatement();
results = stmt.executeQuery(query);
while(results.next()){

Understanding join order for 3 or more tables

I have an old query that was using *= operator. Right now, the query has where clause like below
Table1.Column1 *= Table2.Column1
AND Table1.Column2 *= Table3.Column1
if (some conditions in C# script) //this whole clause is generated by C# function based on different conditions
AND Table1.Column3 *= Table4.Column1
I have to rewrite it to use left join, because well, we are not dinosaurs anymore, and are moving to SQL server 2014 (from sql server 2000). Anyway, I have rewritten the query like
From Table1
Left Join Table2 On Table1.Column1 = Table2.Column1
Left Join Table3 On Table1.Column2 = Table3.Column1
Left Join Table4 On Table1.Column3 = Table4.Column1
I believe this should provide me the same resultset, but it is not. Clearly SQL Server is not following the same join order in both cases. So, I have to figure out the exact order the old query is following, and how to recreate the same order.
P.S. I don't have much understanding about the code. But, I can post the complete function here, in case if it helps someone understand the situation better.
Edit:
The exact query builder function, I am using.
public virtual FANUC.Common.BaseClasses.Row[] GetCustomersForPopup( FANUC.Common.BaseClasses.Row objListCustomerFilter, FANUC.Common.BaseClasses.PagingEventArgs e ) {
string strConnector = " WHERE ";
string strANDClause = "";
string strSQLQuery = " SELECT "
+ " TBL_Company_Master.CMPM_Company_ID,"
+ " TBL_Company_Master.CMPM_Company_Name,"
+ " " + ( ( FANUCUser )Thread.CurrentPrincipal.Identity ).DBUser + ".fnGetRefCodeValue( CMPM_Company_Type_ID ) AS CMPM_CompanyTypeID,"
+ " TBL_Company_Master.CMPM_Company_NickName,"
+ " TBL_Company_Master.CMPM_Service_Center_ID,"
+ " TBL_Company_Master.CMPM_Company_BranchName,"
+ " TBL_Company_Master.CMPM_Black_Listed_Flag,"
+ " TBL_Company_Master.CMPM_Prohibited_Company_Flag,"
+ " " + ( ( FANUCUser )Thread.CurrentPrincipal.Identity ).DBUser + ".fnGetRefCodeValue( TBL_Company_Master.CMPM_Status ) AS CMPM_Status,"
+ " TBL_Company_Master.CMPM_City_Location_ID AS CMPM_City_Location_ID,"
+ " TBL_City_Location_Master.CLIM_City_Name AS CLIM_City_Name, "
+ " TBL_Company_Master.CMPM_Country_ID AS CMPM_Country_ID,"
+ " TBL_Country_Master.CRIM_CountryName, "
+ " TBL_Company_Master.CMPM_Night_Call_Applicable_flag,"
+ " TBL_Company_Master.CMPM_Default_currency_for_transaction,"
+ " TBL_Company_Master.CMPM_Telephone_No, "
+ " TBL_Customer_Contact_Master.CNTM_ContactPersonName, "
+ " TBL_Customer_Contact_Master.CNTM_Section_Name, "
+ " TBL_Company_Master.Use_Count, "
+ " TBL_Company_Master.CMPM_Self_Company_Indicator, "
+ " TBL_Company_Master.CMPM_Transport_Time ";
string strFromClause = " FROM TBL_Company_Master, "
+ " TBL_Service_Center_Master, "
+ " TBL_City_Location_Master, "
+ " TBL_Country_Master, "
+ " TBL_Customer_Contact_Master";
strANDClause += " AND TBL_Company_Master.CMPM_Service_Center_ID *= TBL_Service_Center_Master.SCRM_Service_Center_ID "
+ " AND TBL_Company_Master.CMPM_City_Location_ID *= TBL_City_Location_Master.CLIM_City_ID "
+ " AND TBL_Company_Master.CMPM_Country_ID *= TBL_Country_Master.CRIM_CountryID ";
if ( objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null || objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null || Convert.ToInt32( objListCustomerFilter[ "CUTM_Customer_Type_ID" ] ) == 120 )
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID *= TBL_Customer_Contact_Master.CNTM_Customer_ID ";
else
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID = TBL_Customer_Contact_Master.CNTM_Customer_ID " ;
strANDClause += " AND TBL_Customer_Contact_Master.CNTM_Default_Flag = 'Y' ";
strANDClause += " AND CMPM_Active_Flag != 'N'";
if ( objListCustomerFilter["CUTM_Customer_Type_ID"] != null && Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"]) != "" ) {
strFromClause += " ,TBL_Customer_Type_Mapping ";
strANDClause += " AND CUTM_Customer_ID = CMPM_Company_ID " + " AND CUTM_Customer_Type_ID = "+Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"]);
}
if ( objListCustomerFilter["CMPM_Company_Type_ID"] != null && Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"]) != "" && Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"]) != Constants.ALL ) {
strANDClause += " AND CMPM_Company_Type_ID IN ("+Convert.ToString(objListCustomerFilter["CMPM_Company_Type_ID"])+","+Constants.COMPANY_TYPE_BOTH+") ";
}
if ( !Convert.ToString( objListCustomerFilter[ Constants.PAYMENT_REQD ] ).Equals(Constants.CONST_NO ) ) {
strSQLQuery += ", TBL_Company_Payment_Terms.CMPT_Payment_Term_Description "
+ ", TBL_Company_Payment_Terms.CMPT_Payment_Term_ID ";
strFromClause += " ,TBL_Company_Payment_Terms ";
if((objListCustomerFilter[Constants.IS_CALLING_CUSTOMER] != null) ||(objListCustomerFilter[Constants.IS_END_USER] != null) )
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID *= TBL_Company_Payment_Terms.CMPT_Company_ID "
+ " AND TBL_Company_Payment_Terms.CMPT_Default = 'Y' ";
else
strANDClause += " AND TBL_Company_Master.CMPM_Company_ID = TBL_Company_Payment_Terms.CMPT_Company_ID "
+ " AND TBL_Company_Payment_Terms.CMPT_Default = 'Y' ";
if ( objListCustomerFilter[ "CMPM_Company_Type_ID" ] != null && Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] ) != Constants.COMPANY_TYPE_BOTH && Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] ) != Constants.ALL )
strANDClause += " AND CMPT_Company_Type_ID = " + Convert.ToString( objListCustomerFilter[ "CMPM_Company_Type_ID" ] );
}
strANDClause += " AND CMPM_Subsidiary_Code = '"+((FANUCUser)Thread.CurrentPrincipal.Identity).SubsidiaryCode+"'";
Row objFilter = new Row();
objFilter["CMPM_Company_ID"] = objListCustomerFilter["CMPM_Company_ID"];
objFilter["CMPM_Black_Listed_Flag"] = objListCustomerFilter["CMPM_Black_Listed_Flag"];
objFilter["CMPM_Prohibited_Company_Flag"] = objListCustomerFilter["CMPM_Prohibited_Company_Flag"];
objFilter["CMPM_Status"] = objListCustomerFilter["CMPM_Status"];
objFilter["CMPM_Company_Name~like"] = objListCustomerFilter["CMPM_Company_Name"];
objFilter["CMPM_Company_NickName~like"] = objListCustomerFilter["CMPM_Company_NickName"];
objFilter["CMPM_Telephone_No~like"] = objListCustomerFilter["CMPM_Telephone_No"];
objFilter["CMPM_FAX_No"] = objListCustomerFilter["CMPM_FAX_No"];
objFilter["CMPM_Service_Center_ID"] = objListCustomerFilter["CMPM_Service_Center_ID"];
objFilter["CMPM_Billing_Company_ID"] = objListCustomerFilter["CMPM_Billing_Company_ID"];
objFilter["CMPM_Shipping_Company_ID"] = objListCustomerFilter["CMPM_Shipping_Company_ID"];
objFilter["CMPM_City_Location_ID"] = objListCustomerFilter["CMPM_City_Location_ID"];
objFilter["CMPM_State_ID"] = objListCustomerFilter["CMPM_State_ID"];
objFilter["CMPM_Country_ID"] = objListCustomerFilter["CMPM_Country_ID"];
objFilter["CMPM_Grp_Parent_Company_ID"] = objListCustomerFilter["CMPM_Grp_Parent_Company_ID"];
objFilter["CMPM_Night_Call_Applicable_Flag"] = objListCustomerFilter["CMPM_Night_Call_Applicable_Flag"];
objFilter["CMPM_Default_currency_for_transaction"] = objListCustomerFilter["CMPM_Default_currency_for_transaction"];
objFilter["CMPM_Company_local_registration_No~like"] = objListCustomerFilter["CMPM_Company_local_registration_No"];
objFilter["CMPM_Company_central_registration_No~like"] = objListCustomerFilter["CMPM_Company_central_registration_No"];
objFilter["CMPM_Insurance_Policy_No~like"] = objListCustomerFilter["CMPM_Insurance_Policy_No"];
objFilter["CMPM_Active_Flag"] = objListCustomerFilter["CMPM_Active_Flag"];
objFilter["CMPM_Company_BranchName~like"] = objListCustomerFilter["CMPM_Company_BranchName"];
objFilter["CMPM_Company_BranchName_LocalLanguage~like"] = objListCustomerFilter["CMPM_Company_BranchName_LocalLanguage"];
objFilter["CMPM_Postal_Code"] = objListCustomerFilter["CMPM_Postal_Code"];
objFilter["CMPM_Web_Site~like"] = objListCustomerFilter["CMPM_Web_Site"];
objFilter["CMPM_Distance"] = objListCustomerFilter["CMPM_Distance"];
if ( objListCustomerFilter["CMPM_Self_Company_Indicator"] != null && Convert.ToString(objListCustomerFilter["CMPM_Self_Company_Indicator"]) != Constants.ALL )
objFilter[ "CMPM_Self_Company_Indicator" ] = objListCustomerFilter["CMPM_Self_Company_Indicator"];
CommonBQ objCommonBQ = new CommonBQ();
string strSearchClause = objCommonBQ.CreateFilter( objFilter );
string strFinalString = "";
if ( !strSearchClause.Equals( "" ) ) strFinalString = strSQLQuery + strFromClause + strConnector + strSearchClause + strANDClause;
else {
strSQLQuery += strFromClause + strConnector + strANDClause;
int iFirstPos = strSQLQuery.IndexOf( "AND", 0 );
string strFirstPart = strSQLQuery.Substring( 0, iFirstPos );
string strSecondPart = strSQLQuery.Substring( iFirstPos + 3, strSQLQuery.Length - iFirstPos - 3 );
strFinalString = strFirstPart + strSecondPart;
}
return GetRows( strFinalString, CreateParameterArray( objListCustomerFilter ), CommandType.Text, null, e );
}
There are a few things you should update in this query:
Use Table Alias in select clause instead of complete table names.
TBL_Customer_Contact_Master is being joined based on condition:
objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null ||
objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null ||
Convert.ToInt32( objListCustomerFilter[ "CUTM_Customer_Type_ID" ] )
== 120 ) If this holds true then there's a Left Join else Inner join.
So update the statements as:
string strFromClause =
" FROM TBL_Company_Master TCM " +
" Left Join TBL_Service_Center_Master TSC on
TCM.CMPM_Service_Center_ID = TSC.SCRM_Service_Center_ID " +
"Left Join TBL_City_Location_Master TCL on
TCM.CMPM_City_Location_ID = TCL.CLIM_City_ID " +
"Left Join TBL_Country_Master TC on
TCM.CMPM_Country_ID = TC.CRIM_CountryID ";
Update condition 1 as:
if ( objListCustomerFilter[ Constants.IS_CALLING_CUSTOMER ] != null ||
objListCustomerFilter[ Constants.IS_PAYEE_CUSTOMER ] != null || Convert.ToInt32(
objListCustomerFilter[ "CUTM_Customer_Type_ID" ] ) == 120 )
strFromClause += " Left join TBL_Customer_Contact_Master TCCM on TCM.CMPM_Company_ID
= TCCM.CNTM_Customer_ID ";
else
strFromClause += " Inner join TBL_Customer_Contact_Master TCCM on TCM.CMPM_Company_ID
= TCCM.CNTM_Customer_ID ";
Then update condition 2 as:
if ( objListCustomerFilter["CUTM_Customer_Type_ID"] != null && Convert.ToString
(objListCustomerFilter["CUTM_Customer_Type_ID"]) != "" ) {
strFromClause += "Left join TBL_Customer_Type_Mapping on CUTM_Customer_ID = CMPM_Company_ID AND CUTM_Customer_Type_ID = "+Convert.ToString(objListCustomerFilter["CUTM_Customer_Type_ID"] ; }
And condition 3 as:
if((objListCustomerFilter[Constants.IS_CALLING_CUSTOMER] != null) ||(objListCustomerFilter
[Constants.IS_END_USER] != null) )
strFromClause += " Left Join TBL_Company_Payment_Terms TCPT
On TCM.CMPM_Company_ID = TCPT.CMPT_Company_ID AND TCPT.CMPT_Default = 'Y' ";
else
strFromClause += " Inner Join TBL_Company_Payment_Terms TCPT
On TCM.CMPM_Company_ID = TCPT.CMPT_Company_ID AND TCPT.CMPT_Default = 'Y' ";
I might have missed a few commas and semi - colons here and there but it should give you an idea where things might be missing. Hope this helps!!!
The order doesn't matter in left outer joins so please stay assured, it's not causing it. My guess would be the if statments might be causing the difference in results.
If you can share the table data or the outputs, it could be figured out.
The difference is in how additional where clause filters are applied for columns in the outer joined tables.
With this:
select *
from a
left outer join b on a.id = b.id
where
b.other_col = 'test'
The result will contain only rows where the row in b was found and the other_col column in b has the value test.
Comparing to this:
select *
from a, b
where
a.id *= b.id
and b.other_col = 'test'
This will find all rows in a. And it will include the columns from b for rows where b.other_col = 'test'.
So taking the second query and converting it to one with a left join, one of the following would give the same output:
-- 1.
select *
from a
left outer join b on a.id = b.id and b.other_col = 'test'
-- 2.
select *
from a
left outer join
(
select *
from b
where other_col = 'test'
) as b on a.id = b.id

Can not get data from column in table when value ""

I have a prolem in my project when i get value from column in table. I create database by c# code.
This is my code:
public static int typeTransactionIncome = 1; // thu
public static int typeTransactionExpense = 2; // chi
public static int typeTransactionDebt = 3; // nợ
public static int typeTransactionLoan = 4; // cho vay
public static string tableNameCategory = "categories";
private static string createTableTransactionString = "CREATE TABLE IF NOT EXISTS \"transactions\" " + "(\"id\" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,"
+ "\"name\" VARCHAR(140) ," + "\"amount\" FLOAT NOT NULL DEFAULT (0) ," + "\"type\" INTEGER NOT NULL ,"
+ "\"created_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ," + "\"displayed_date\" DATETIME NOT NULL DEFAULT (CURRENT_DATE) ,"
+ "\"cat_id\" INTEGER NOT NULL DEFAULT (0) ," + "\"with_person\" VARCHAR(50)," + "\"remind_date\" DATETIME,"
+ "\"remind_num\" INTEGER DEFAULT (0) ," + "\"note\" VARCHAR(140) ," + "\"status\" BOOL NOT NULL DEFAULT (0),"
+ "\"user_id\" INT NOT NULL DEFAULT (1))";
This is insert code: Insert some column, and there 2 insert menthod
public void insertNewIncome(string _name, string _note, double _amount, DateTime _displayedDate, int _catId, int _usertId)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, name, note, amount, displayed_date, cat_id, user_id) values (#type, #name, #note, #amount, #displayed_date, #cat_id, #user_id)";
cmd.Parameters.Add("#type", typeTransactionIncome);
cmd.Parameters.Add("#name", _name);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _displayedDate);
cmd.Parameters.Add("#cat_id", _catId);
cmd.Parameters.Add("#user_id", _usertId);
cmd.ExecuteNonQuery();
//MessageBox.Show("income");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void insertNewDebt(string _debter, string _note, double _amount, DateTime _ngay_vay, DateTime _ngay_tra, int _user_id)
{
try
{
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO " + tableNameTransaction + "(type, with_person, note, amount, displayed_date, remind_date, user_id) VALUES (#type, #with_person, #note, #amount, #displayed_date, #remind_date, #user_id)";
cmd.Parameters.Add("#type", typeTransactionDebt);
cmd.Parameters.Add("#with_person", _debter);
cmd.Parameters.Add("#note", _note);
cmd.Parameters.Add("#amount", _amount);
cmd.Parameters.Add("#displayed_date", _ngay_tra);
cmd.Parameters.Add("#remind_date", _ngay_tra);
cmd.Parameters.Add("#user_id", _user_id);
cmd.ExecuteNonQuery();
//MessageBox.Show("debt");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
closeConnection();
}
}
I was insert some records to table by insertNewDebt and insertNewIncome menthod, it was ok, not any error.
This is menthod that get all record in table:
public List<ItemTransaction> loadTransactionAll(DateTime _start_date, DateTime _end_date, int _user_id)
{
List<ItemTransaction> li = new List<ItemTransaction>();
openConnection();
SqliteCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT transactions.id AS master_id,transactions.name,transactions.amount,transactions.type,transactions.created_date, transactions.displayed_date,transactions.cat_id, transactions.with_person,transactions.remind_date,remind_num, transactions.note,transactions.status,transactions.user_id,categories.id,categories.name,categories.icon,categories.type,IFNULL(sub_amount,0) AS sub_amount "
+ "FROM transactions "
+ "LEFT JOIN categories ON transactions.cat_id = categories.id "
+ "LEFT JOIN ("
+ "SELECT sub_trans_id, IFNULL(SUM(sub_amount),0) AS sub_amount "
+ "FROM (SELECT trans_id AS sub_trans_id,SUM(amount) AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_income "
+ "GROUP BY sub_trans_id "
+ "UNION ALL SELECT trans_id AS sub_trans_id,SUM(amount) * -1 AS sub_amount "
+ "FROM sub_transactions "
+ "WHERE type = #type_expense GROUP BY sub_trans_id) GROUP BY sub_trans_id) ON sub_trans_id = master_id "
+ "WHERE (displayed_date BETWEEN #start_date AND #end_date) "
+ "AND transactions.user_id = #user_id "
+ "ORDER BY displayed_date DESC, transactions.type ASC, status ASC";
cmd.Parameters.Add("#type_income", DatabaseProccess.typeTransactionIncome);
cmd.Parameters.Add("#type_expense", DatabaseProccess.typeTransactionExpense);
cmd.Parameters.Add("#start_date", _start_date);
cmd.Parameters.Add("#end_date", _end_date);
cmd.Parameters.Add("#user_id", _user_id);
SqliteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
ItemTransaction item = new ItemTransaction();
item.master_id = reader.GetInt32(0);
item.name = reader.GetString(1);
item.amount = reader.GetDouble(2);
item.type = reader.GetInt32(3);
item.created_date = reader.GetDateTime(4);
item.displayed_date = reader.GetDateTime(5);
item.cat_id = reader.GetInt32(6);
item.with_person = reader.GetString(7);
item.remind_date = reader.GetDateTime(8);
item.remind_num = reader.GetInt32(9);
item.note = reader[10].ToString();
item.status = reader.GetBoolean(11);
item.user_id = reader.GetInt32(12);
item.setCategory(reader.GetInt32(13), reader.GetString(14), reader.GetString(15), reader.GetInt32(16));
item.sub_amount = reader.GetDouble(17);
li.Add(item);
}
return li;
}
But when i execute insert:
insertNewIncome("", "note", "1000", DateTime.Today, 1, 1);
with 'name' field value = ""
I can not read 'name' field. Debug say:
view error screen shot here, please
And this is ItemTransaction class:
view ItemTransaction class here, please
I don't understand this error.
Please, thank
You're getting this error because name is NULL.
The following if statement would fix this:
if (reader(1) != null){
item.name = reader.GetString(1);
}
However if you're passing the value "", then this shouldn't be stored as NULL.
Check your database and see what the value is. Perhaps you have a trigger in place which updates "" to null.