Error Date in SQL Query - sql

I have a problem with my SQL query.
The error is :
The conversion of a varchar data type to a smalldatetime data type resulted in an" + " out-of-range value.
I tried to use the CONVERT function to remedy it but in vain.
public static List<string> Helper_Statistic_6(DateTime start, DateTime end) {
DateTime dateStart = start;
DateTime dateEnd = end;
string query = "SELECT ... FROM ... WHERE DATE BETWEEN CONVERT(VARCHAR(10),'" + dateStart+ "',120) and CONVERT(VARCHAR(10),'" + dateEnd+ "',120) ";
}

I suspect you're using C# with Microsoft SQL Server.
In any case, to avoid the woes of code injection, one should try to use parametized SQL. Allow the compiler take care of marshalling a C# Date to a SQL Date.
EDIT: As per #marc_s suggestion, you should beware using reserved SQL keywords as column names, otherwise, protect them from being treated as SQL keywords by using [ ] symbols, i.e. [DATE] isntead of DATE.
I would expect the syntax to look like this:
public static void Run_Helper_Statistic_6(DateTime start, DateTime end)
{
using (SqlCommand command = new SqlCommand(
"SELECT ... FROM ... WHERE [DATE] BETWEEN #start and #end", connection))
{
command.Parameters.Add(new SqlParameter("start", start));
command.Parameters.Add(new SqlParameter("end", end));
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// ...
}
}
}

Related

How to get year from string date c#

I have string date in sql server, and I want to retrieve all the rows greater than or equal the year of 2018 using ADO.Net. This is what I've accomplished but the result.HasRows() returns false although I already have rows in that table.
Is it something related to Culture?
UPDATE:
the problem was in data itself. there were some date in different format. it works now.
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT *
$"FROM [dbo].[tableName] " +
$"WHERE Year(CAST([tableNmae].Date as datetime)) >= {2018} ";
using (var result = command.ExecuteReader())
{
if (result.HasRows)
{
while (result.Read())
{}
}
}
}
You cannot use CAST for the string type. You should use CONVERT instead of CAST
Why 104? Because I took this website as a reference.
http://www.sqlusa.com/bestpractices/datetimeconversion/
using (var command = connection.CreateCommand())
{
command.CommandText = $"SELECT *
$"FROM [dbo].[tableName] " +
$"WHERE Year(CONVERT(DATETIME,[tableNmae].Date,104)) >= {2018} ";
using (var result = command.ExecuteReader())
{
if (result.HasRows)
{
while (result.Read())
{}
}
}
}
NOTE: To use CONVERT, the column must not be of ntext type.
If you use it you will get this error.
Explicit conversion from data type ntext to datetime is not allowed.
Sample error if you don't use the correct dial type

Store date and time in sql server 2012 using c#

i want to store date and time in SQL Server 2012 using asp.net but generate some error "Conversion failed when converting date and/or time from character string."
protected void btn Submit_Click(object sender, EventArgs e)
{
lbldate.Text = Convert.ToDateTime(this.txtdate.Text).ToString("dd/MM/yyyy");
lbltime.Text = Convert.ToDateTime(this.txttime.Text).ToLongTimeString();
TimeSpan time = new TimeSpan();
time.ToString();
SqlConnection con = new SqlConnection(#"Data Source=DESKTOP-O6SE533;Initial Catalog=Datertime;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False");
SqlCommand cmd = new SqlCommand("insert date,time into DateTimedemo values('" +txtdate.Text + "','"+txttime.Text+"')", con);
con.Open();
int r = cmd.ExecuteNonQuery();
if (r > 0)
{
Response.Write("success");
}
else
{
Response.Write("failed");
}
}
Use parameterized SQL instead of building the SQL dynamically. This avoids SQL injection attacks and string formatting differences, as well as making the code clearer.
Additionally, I believe both "date" and "time" are keywords in T-SQL, so you should put them in square brackets when using them as field names.
You should attempt to perform as few string conversions as possible. Without knowing exactly what your web page looks like it's hard to know exactly how you want to parse the text, but assuming that Convert.ToDateTime is working for you (sounds worryingly culture-dependent to me) you'd have code like this:
protected void btn Submit_Click(object sender, EventArgs e)
{
// TODO: Ideally use a date/time picker etc.
DateTime date = Convert.ToDateTime(txtdate.Text);
DateTime time = Convert.ToDateTime(txttime.Text);
// You'd probably want to get the connection string dynamically, or at least have
// it in a shared constant somewhere.
using (var con = new SqlConnection(connectionString))
{
string sql = "insert [date], [time] into DateTimeDemo values (#date, #time)";
using (var cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("#date", SqlDbType.Date).Value = date;
cmd.Parameters.Add("#time", SqlDbType.Time).Value = time.TimeOfDay;
int rows = cmd.ExecuteNonQuery();
string message = rows > 0 ? "success" : "failed";
Response.Write(message);
}
}
}
I've guessed at what SQL types you're using. If these are meant to represent a combined date and time, you should at least consider using a single field of type DateTime2 instead of separate fields.

System.Data.SqlClient.SqlException: Incorrect syntax near '2017-03-21'

protected void btnBeds_click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
con.Open();
String checkBeds = "SELECT Count (*) FROM Bed WHERE bedID NOT IN (SELECT DISTINCT(bedID) FROM Booking where startDate>='"+TxtArrivalDate.Text+"' and endDate<= '"+txtDepartureDate.Text+"'";
SqlCommand showcheckBeds = new SqlCommand(checkBeds, con);
ResultLabel.Text = showcheckBeds.ExecuteScalar().ToString();
con.Close();
}
I'm trying to display the amount of free beds there are in the database and im getting this error.
Always use parameters in your queries
Always wrap connections and other types that implement IDisposable in using statements to ensure the resource is released
Use the correct types in your database and match that type with the passed in parameter. Example: do not pass in a string for a date, do not store dates as strings.
Your actual problem was a missing ) at the end of your sql statement as pointed out by #Damien_The_Unbeliever
Updated code with changes:
const string checkBeds = "SELECT Count (*) FROM Bed WHERE bedID NOT IN (SELECT DISTINCT(bedID) FROM Booking where startDate >= #startDate and endDate<= #endDate)";
using(SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString))
using(SqlCommand showcheckBeds = new SqlCommand(checkBeds, con))
{
showcheckBeds.Parameters.Add(new SqlParameter("#startDate", SqlDbType.DateTime){Value = DateTime.Parse(TxtArrivalDate.Text) });
showcheckBeds.Parameters.Add(new SqlParameter("#endDate", SqlDbType.DateTime){Value = DateTime.Parse(txtDepartureDate.Text) });
con.Open();
ResultLabel.Text = showcheckBeds.ExecuteScalar().ToString();
}
Note: In the code above I used a direct DateTime.Parse to get an actual DateTime instance to pass as a parameter. It would probably be advisable to change that either to ParseExact or to provide a CultureInfo instance to the method.
Try This
String checkBeds = "SELECT Count (*) FROM Bed WHERE bedID NOT IN (SELECT DISTINCT(bedID) FROM Booking where startDate>='"+Convert.ToDateTime( TxtArrivalDate.Text).ToStrin("dd MMM yyyy")+"' and endDate<= '"+Convert.ToDateTime(txtDepartureDate.Text).ToString("dd MMM yyyy")+"'";

Spring jdbcTemplate query always returns null irrespective of data in database

I need to fetch a sum value from database based on date range. I tried using Spring jdbcTemplate in the following ways. But it doesn't return anything.
public void getTotal(String from, string toDate){
String totalSql="select sum(b.finalAmount) as total from example a, example b "+
"where a.created >= TO_TIMESTAMP(:fromDate, 'MM-DD-YYYY') AND a.created < TO_TIMESTAMP(:toDate, 'MM-DD-YYYY hh24:mi:ss') "+
"and a.tradein_id=b.tradein_id";
List<Integer> checkAmt = jdbcTemplate.query(sql, new RowMapper<Integer>() {
#Override
public Integer mapRow(ResultSet rs, int rowNum) throws SQLException
{
int check = rs.getInt("TOTAL");
return check;
}
}, fromDate,toDate);
int checkAmount = jdbcTemplate.queryForObject(
totalSql, new Object[]{fromDate, toDate},Integer.class);
}
When I hardcode the fromDate and toDate in query, it works fine. I assume there is something wrong with the select parameters I am sending in.
Both from date and todate are String values from front end of the format 08/09/2016.
The SQL is using named parameters but the code is sending a list of arguments. Either use a NamedParameterJdbcTemplate and change how you're passing in arguments, or use a JdbcTemplate and change the SQL to use the ? placeholder instead of named arguments.
If you use NamedParameterJdbcTemplate, you have to refer to the parameters by name in the SQL, and you have to provide names when passing in the arguments. Put them in a map, like this (from the spring-jdbc documentation):
public int countOfActorsByFirstName(String firstName) {
String sql = "select count(*) from T_ACTOR where first_name = :first_name";
SqlParameterSource namedParameters = new MapSqlParameterSource("first_name", firstName);
return this.namedParameterJdbcTemplate.queryForObject(sql, namedParameters, Integer.class);
}
Alternatively you can provide the arguments like this:
Map args = new HashMap();
args.put("fromDate", fromDate);
args.put("toDate", toDate);
jdbcTemplate.queryForObject(sql, args, Integer.class);
If you don't want to use named parameters, change the SQL to look like
String totalSql= "select sum(b.finalAmount) as total from example a, example b "+
"where a.created >= TO_TIMESTAMP(?, 'MM-DD-YYYY') AND a.created < TO_TIMESTAMP(?, 'MM-DD-YYYY hh24:mi:ss') "+
"and a.tradein_id=b.tradein_id"
and leave the rest alone.

Sending datetime value to a stored procedure

I want to send just date to a stored procedure and I wrote this C# code:
string[] pr = { "/" };
string[] s = txtStartDate.Text.Split(pr, StringSplitOptions.None);
term.Start_date = new DateTime(Convert.ToInt32(s[0]), Convert.ToInt32(s[1]), Convert.ToInt32(s[2])).Date;
s = txtEndDate.Text.Split(pr, StringSplitOptions.None);
term.End_date = new DateTime(Convert.ToInt32(s[0]),Convert.ToInt32(s[1]),Convert.ToInt32(s[2])).Date;
and I send it to the stored procedure like this:
public bool AddNewTerm(Term term)
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter ("#termName",term.TermName),
new SqlParameter ("#start_date",term.Start_date),
new SqlParameter ("#end_date",term.End_date)
};
return SqlDBHelper.ExecuteNonQuery("AddNewTerm", CommandType.StoredProcedure, parameters);
}
but when it goes to the stored procedure say this:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.
I see other topic but they cant help me
This is the stored procedure code:
ALTER PROCEDURE dbo.AddNewTerm
(
#termName varchar(50),
#start_date date,
#end_date date
)
AS
insert into term(termName, start_date, end_date)
values(#termName, #start_date, #end_date)
RETURN
Where is the problem?
I find my answer by changing my way
I used PersianCalendar Class and store it varchar.
The error message talks about a lower limit of 1/1/1753, so, supposing that you have parsed correctly your inputs (30/6/1390) the message seems clearly indicate that the two column start_date and end_dateare of type datetimethat has a lower limit of 1/1/1753.
So, to store a date with year less than 1753 you need a datetime2 or date column that have a lower limit of 1/1/0001
Here a quick reference for the two datatypes
There is another problem in your code. You add the parameters to the array without specyfing their SqlDbType and in this way the Date are added as DateTime parameters that of course cannot accept a value below 1/1/1753. A workaround for your specific code could be.
public bool AddNewTerm(Term term)
{
List<SqlParameter> parameters = new List<SqlParameter>()
{
new SqlParameter("#termName",SqlDBType.VarChar, 50) {Value = term.TermName},
new SqlParameter("#start_date",SqlDBType.DateTime2, 0) {Value = term.Start_Date},
new SqlParameter("#end_date",SqlDBType.DateTime2, 0) {Value = term.End_Date},
};
return SqlDBHelper.ExecuteNonQuery("AddNewTerm", CommandType.StoredProcedure, parameters.ToArray());
}