I have to take 2 values from DateTimePicker and then compare their values with that in database.
Code:
string dt_start = dateTimePicker1.Value.ToShortDateString();
string dt_end = dateTimePicker2.Value.ToShortDateString();
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between " + dt_start + " and " + dt_end + " ";
It is not showing any error, but I am not getting output values.
Access uses # for dates. This should work:
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between #" + dt_start + "# and #" + dt_end + "#";
try the following select statement:
string mySelectQuery = "Select * from " + out_table + " WHERE [Date] Between '" + dt_start + "' and '" + dt_end + "' ";
Related
This question already has answers here:
Incorrect syntax near 'GO'
(9 answers)
Closed 2 years ago.
I have a SQL query which creates a database and declares the path of an mdf and its log files. The same query works when I execute it in management studio (I am sure it's the same query I copy paste it from SQL Profiler) but gives a syntax error below:
incorrect syntax near go.
I have tried using executeNonQuery, ExecuteReader and ExecuteScalar to execute my query but nothing worked. It was giving syntax error due to the lack of newlines in query from my code hence the newline methods in the query. Any help would be appreciated.
Visual Studio code:
string truvamdf = #"C:\Truva\Data\"+VeritabaniAdiTextBox.Text+".mdf";
string truvaldf = #"C:\Truva\Data\"+VeritabaniAdiTextBox.Text+"_log.ldf";
string connectionString = (#"" + File.ReadAllText(#"C:\Truva\Ivdexcel\IVDVeritabaniconfig.ini") + "");
string cmdtext = "" +
"USE[master] " + Environment.NewLine + "" +
"GO " + Environment.NewLine + "" +
"DECLARE #mdfPath NVARCHAR(max), #ldfPath NVARCHAR(max) , #SQL NVARCHAR(MAX), #instName NVARCHAR(max) = '" + VeritabaniAdiTextBox.Text + "' " + Environment.NewLine + "" +
"SELECT #mdfPath = '" + truvamdf + "' " + Environment.NewLine + " " +
",#ldfPath = '" + truvaldf + "' " + Environment.NewLine + " " +
"FROM master.sys.master_files WHERE database_id = 1 " + Environment.NewLine + "" +
"SELECT #SQL = " + Environment.NewLine + "" +
"'CREATE DATABASE ["+VeritabaniAdiTextBox.Text+ "] " + Environment.NewLine + " " +
"CONTAINMENT = NONE " + Environment.NewLine + " " +
"ON PRIMARY " + Environment.NewLine + "" +
"(NAME = N'''+#instName+''', FILENAME = N'''+#mdfPath+''' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB ) " + Environment.NewLine + " " +
" LOG ON " + Environment.NewLine + " " +
" (NAME = N'''+#instName+'_log'', FILENAME = N'''+#ldfPath+''' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10 %)' "+Environment.NewLine+ " " + Environment.NewLine + "" +
"EXECUTE(#SQL) " + Environment.NewLine + " " + Environment.NewLine + "" +
" GO ";
// try
// {
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand cmd = new SqlCommand(cmdtext, connection);
cmd.ExecuteNonQuery();
}
The same SQL query in SSMS:
USE[master]
GO
DECLARE #mdfPath NVARCHAR(max), #ldfPath NVARCHAR(max) , #SQL NVARCHAR(MAX), #instName NVARCHAR(max) = 'dddssd'
SELECT #mdfPath = 'C:\Truva\Data\dddssd.mdf'
,#ldfPath = 'C:\Truva\Data\dddssd_log.ldf'
FROM master.sys.master_files WHERE database_id = 1
SELECT #SQL =
'CREATE DATABASE [dddssd]
CONTAINMENT = NONE
ON PRIMARY
(NAME = N'''+#instName+''', FILENAME = N'''+#mdfPath+''' , SIZE = 5120KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
LOG ON
(NAME = N'''+#instName+'_log'', FILENAME = N'''+#ldfPath+''' , SIZE = 2048KB , MAXSIZE = 2048GB , FILEGROWTH = 10 %)'
EXECUTE(#SQL)
GO
I just deleted the GO statements from the query and it works now!!
I have a SQL statement for querying in MS Access. I want to get the result of the transaction between dates.
This is my code:
DateTime pFromNew = Convert.ToDateTime(this.dateTimePicker1.Value.ToString("yyyy-MM-dd"));
DateTime pToNew = Convert.ToDateTime(this.dateTimePicker2.Value.ToString("yyyy-MM-dd"));
string pFrom = "#" + pFromNew.ToString() + "#";
string pTo = "#" + pToNew.ToString() + "#";
chrTrans.Series["Class"].Points.Clear();
oconn.Open();
OleDbCommand cmd = oconn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
//+ "' and valuedate between '"+ this.dateTimePicker1.Text +"' and '"+ this.dateTimePicker2.Text +"'";
cmd.ExecuteNonQuery();
What is wrong with this statement?
I always get this error:
DATA Type mismatch in criteria expression.
Remove the single quotes you have in your string... I will show you...
This line:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between '" + pFrom + "' and '" + pTo + "'";
Should be:
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo;
The reason is that you already concatenated a # symbol around your date strings--and the single quote thus is not needed.
You are making this too complicated, converting back and forth three times.
It can be reduced to:
string pFrom = "#" + this.dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd") + "#";
string pTo = "#" + this.dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd") + "#";
// snip
cmd.CommandText = "Select ClassType,Nametree,TransWeight,Valuedate from tblTrans where Nametree = '" + this.cboNametree.Text.Trim() + "' and valuedate between " + pFrom + " and " + pTo + "";
I'm trying to write to a database and am getting the "Input String Was Not In Correct Format" error. I'm assuming it's the data types on the last two columns but I'm not sure how to change. In SQL Server, they are both of the money datatype. Code below:
string query = null;
for (int i = 0; i < result.Tables[0].Rows.Count; i++)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
query = "INSERT INTO Upload(Email, TimeStamp, EmployeeId, Name, Title, Department, Race, Gender, AnnualizedBase, AnnualizedTCC) VALUES ('"
+ System.Web.HttpContext.Current.User.Identity.GetUserId() + "', "
+ " '" + DateTime.Now + "', "
+ " '" + result.Tables[0].Rows[i][0].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][1].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][2].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][3].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][4].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][5].ToString() + "', "
+ Convert.ToInt32(result.Tables[0].Rows[i][6]) + ", "
+ Convert.ToInt32(result.Tables[0].Rows[i][7])
+ ")";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
The error Input string was not in correct format is most likely caused by one of the values in your column not being convertible to an int. If the datatype in SQL is money then you should try and convert to a decimal and not an int. Try this for each row:
decimal num;
if (decimal.TryParse(result.Tables[0].Rows[i][6], out num))
{
// use num because it is indeed a decimal (money in SQL)
}
else
{
// What do you want to do? Log it and continue to next row?
}
Also please read Bobby Tales and example of paratmetrized query.
string TJOBCODE1 = ddlJobCode.SelectedItem.Value;
string abc = ddlJobCode.SelectedItem.ToString();
string TJob_Name = abc.Substring(0, abc.IndexOf('['));
string TRo_Name = abc.Substring(abc.LastIndexOf('[') + 1);
TRo_Name = TRo_Name.Replace("]", "");
string TJOBCODE = TJOBCODE1;
SqlCommand fsql = new SqlCommand("SELECT COUNT(*) AS REC FROM [MTS_TV_RO_TC_FINAL] where JOB_CODE='" + TJOBCODE + "' AND AGENCY_CODE in( select agency_code FROM " + tmptvrlbktbl + ")", Global.con1);
SqlDataAdapter Fda1 = new SqlDataAdapter(fsql);
DataTable Fdt1 = new DataTable();
Fda1.Fill(Fdt1);
int DD = Convert.ToInt32(Fdt1.Rows[0].ItemArray.GetValue(0).ToString());
if (DD == 0)
{
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],'" + COMP_FROM + "','" + COMP_TO + "',GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
SqlCommand cmd1 = new SqlCommand(INSQURY, Global.con1);
cmd1.ExecuteNonQuery();
Alert.show1("Data Saved Successfully", this);
}
else
{
Alert.show1("Data Already Saved", this);
return;
}
The code was perfectly fine, there was an issue with the excel sheet. i changed the query to parametrized and changed the excel sheet as well and it worked.
Change insQury to
string INSQURY = " insert into [MTS_TV_RO_TC_FINAL] ([DATE],[CAPTION_NAME],[IST],[DURATION],[AMOUNT],[CRID],[JOB_CODE],[AGENCY_CODE],[STATUS],[TBAND_IN],[TBAND_OUT],[DATE_FROM],[DATE_TO],[CREATE_DATE],[USER_NAME],[REMARKS],[Ro_Name],[Job_Name]) SELECT [DATE],[CAPTION],[IST],[DURATION],[AMOUNT],[CRID],'" + TJOBCODE + "',[Agency_code],[STAT],[TBAND_IN],[TBAND_OUT],COMP_FROM, COMP_TO,GETDATE() AS DT,'" + Global.uname + "' ,[REMARKS],'" + TRo_Name + "','" + TJob_Name + "' FROM " + tmptvrlbktbl + " ORDER BY DATE";
If COMP_FROM and COMP_TO are dates already you don't need to surround them with single quotation marks.
What's wrong with this SQL UPDATE statement?
try
{
int ageValue = Int32.Parse(age.Text);
string updateQuery = "Update \nMyTable \nSet \nFName = '" + fname.Text.ToString() + "',\nLName = '" + lname.Text.ToString() + "',\nAge = " + ageValue + ",\nCome = '" + from.Text.ToString() + "',\nTo = '" + to.Text.ToString() + "' Where Age=" + ageValue + ";";
MessageBox.Show(updateQuery);
OleDbConnection con = new OleDbConnection("provider=Microsoft.JET.OLEDB.4.0; Data Source = Database5.mdb");
OleDbCommand com = new OleDbCommand(updateQuery, con);
con.Open();
com.ExecuteNonQuery();
con.Close();
}
catch (FormatException ex)
{
MessageBox.Show(ex.Message);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
I received that error
Syntax error in Update statement
What is wrong in that SQL Update?
Tools:
Microsoft Access 2003
Microsoft Visual Studio 2010 C#
Please help and thanks in advance
Try getting rid of the \n junk.
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() + "',LName = '" + lname.Text.ToString() + "',Age = " + ageValue + ",Come = '" + from.Text.ToString() + "',To = '" + to.Text.ToString() + "' Where Age=" + ageValue;
Output the result of the concatination and try to run it. If that doesn't work, post the result of the concatination here and someone should be able to help. Without knowing the result of the concatination, it's difficult to know what's wrong.
Try changing the query like this (removing \ns and the final ;)
string updateQuery = "Update MyTable Set FName = '" + fname.Text.ToString() +
"', LName = '" + lname.Text.ToString() + "', Age = " + ageValue +
", Come = '" + from.Text.ToString() + "', To = '" + to.Text.ToString() +
"' Where Age=" + ageValue;
I would suggest you put the Sql Profiler on and trace your update query because it is easy to read the concatenated query string
Hello you can try with this code
StringBuilder stringBuilder = new StringBuilder() ;
stringBuilder.Append("Update MyTable Set FName = ") ;
stringBuilder.Append(fname.Text.ToString()) ;
stringBuilder.Append(",\nLName = ") ;
stringBuilder.Append(lname.Text.ToString()) ;
stringBuilder.Append(",\nAge = ") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(",\nCome = ") ;
stringBuilder.Append(from.Text.ToString()) ;
stringBuilder.Append(",\nTo = ") ;
stringBuilder.Append(to.Text.ToString()) ;
stringBuilder.Append(" Where Age=") ;
stringBuilder.Append(ageValue) ;
stringBuilder.Append(";") ;
var result = stringBuilder.ToString();
This is how I write my inline SQL in C sharp:
string strSQL = "";
strSQL += " Update MyTable Set ";
strSQL += " FName = '" + fname.Text.ToString() + "' ";
strSQL += " ,LName = '" + lname.Text.ToString() + "' ";
strSQL += " ,Age = '" + ageValue + "' ";
strSQL += " ,Come = '" + from.Text.ToString() + "' ";
strSQL += " ,To = '" + to.Text.ToString() + "' ";
strSQL += " Where Age = '" + ageValue + "' ";
Easy to read and works fine.
You can also add this just below your query before you connent to your database:
Response.Write(strSQL);
return;
this will show you whats being posted to the server and makes it a little easier to find errors.