c# query is not returning anything - c#

here is my query:
select reporttime, datapath, finalconc, instrument from batchinfo
join qvalues on batchinfo.rowid=qvalues.rowid where qvalues.rowid
in (select rowid from batchinfo where instrument LIKE '%TF1%' and reporttime
like '10/%/2010%') and compound='ETG' and name='QC1'
i am running it like this:
// Create a database connection object using the connection string
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
// Create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
it does not return any results.
when i try this same query in sql server GUI it returns lots of rows
is there a problem specifically with the syntax of the query for c#?
please note that if i simplify the query like select * from table, there is no issue

Can you try using SqlCommand instead of OleDbCommand?
According to MSDN it: Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database.
So if you really are using SQL Server 2008 you should probably use this. Any reason you are not?

How are you setting up the mySelectQuery string?
Could this be a problem with an escape character?
If you're not doing it already,
string mySelectQuery = #"query text here";

Personally I would run query profiler to see what query (if any) is being run, and then go from there.

Are you sure you are connecting to the same database in your code?
On a side note do you need the inner select? Couldn't you write this query as follows.
select reporttime,
datapath,
finalconc,
instrument
from batchinfo
join qvalues on batchinfo.rowid = qvalues.rowid
where compound = 'ETG'
and name = 'QC1'
and batchinfo.instrument like '%TF1%'
and batchinfo.reporttime like '10/%/2010%'

Edit - Never mind, just read the comment that your date is in a varchar field. Will leave this here since it may still be useful information.
Try this:
reporttime like 'Oct%2010%'
I have a test table here and when I query it using
where LastModified like '11/%/2010%'
no rows are returned, although all of the rows in the table have dates in November 2010. When I run the same query using like 'Nov%2010%', it returns all rows.
Details can be found here:
The LIKE clause can also be used to search for particular dates, as well. You need to remember that the LIKE clause is used to search character strings. Because of this the value which you are searching for will need to be represented in the format of an alphabetic date. The correct format to use is: MON DD YYYY HH:MM:SS.MMMAM, where MON is the month abbreviation, DD is the day, YYYY is the year, HH is hours, MM is minutes, SS is seconds, and MMM is milliseconds, and AM designates either AM or PM.

Related

Syntax error when running SQL command in C#

cmd = new SqlCommand("Select Max(Date_Time) From Daily_Sale ", con); cmd.ExecuteNonQuery();
string date_tim = (string)cmd.ExecuteScalar();
MessageBox.Show("date time" + date_tim);
This shows date time in a message box, but when I call this query:
cmdc = new SqlCommand("Select Total_Sale from Daily_Sale Where Date_Time ="+ date_tim,con);
cmdc.ExecuteNonQuery();
I get a syntax error.
Date_Time is saved as nvarchar(50).
First, you need to use parameters to send data to SQL. Never concatenate strings of data to SQL statement. That's a security hole as it's an open door to SQL Injection attacks.
For more information, read How can prepared statements protect from SQL injection attacks? and Microsoft Docs - How to: Perform Parameterized Queries
Second, Never store dates as strings in your database. For date only values, use the Date data type. For time only values, use the Time data type. For date and time values, use the DateTime2 data type (why not use DateTime?).
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type, and my answer on SO to this question.
Third, you don't need two queries to get the last value of total_sale from the database. You can do that in a single query, without any parameters at all:
SELECT TOP 1 Total_Sale
FROM Daily_Sale
ORDER BY Date_Time DESC
If you want the date time value as well, simply add that to the query:
SELECT TOP 1 Total_Sale, Date_Time
FROM Daily_Sale
ORDER BY Date_Time DESC

Access SQL Delete DateTime not working

I am trying to execute following code for I have hardcoded the date in but it doesn't seem to delete it before I had data mismatch expection.
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
I ran the SQL query in Access and it didn't work. So I generated it using the tools avaliable there and it looks like that:
DELETE Class.ClassDate FROM Class WHERE (((Class.ClassDate)=#12/10/2015#));
Instead of:
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#;";
use
string myQuery = "DELETE FROM Class WHERE Date=#10/12/2015#";
Be sure not to put ; before " in Access SQL in C#
A good reality check is to replace DELETE with SELECT *, if the WHERE clause doesn't return any rows in a SELECT query, it isn't going to delete any either.
Is it possible there is a time component stored in the field Date? The value #10/12/2015# is implicitly #10/12/2015 12:00 AM#, and a test for equality will only return rows that match exactly. If you're actually looking for all rows with any time of day on that date...
WHERE [Date] BETWEEN #10/12/2015# AND #10/12/2015 11:59 PM#
(Not sure if Date is a reserved word in Access -- life is too short to depend on Jet -- but even if it isn't the square brackets won't hurt anything.)

datetime query in SQL

I have to write a query to get rows where date is like current date.
I don't want to compare the the time part but only date part.
Like today's date is 2014-05-03
but in table its in datetime as 2014-05-03 10:08:22
i tried [http://www.w3schools.com/sql/func_convert.asp]
but could not do anything..
my query is like
select *from dbo.param where cvdatetime like '2014-05-03%';
but its does not work although if i use
select *from dbo.param where cvdatetime like '%2014%';
it works so i don't get why "like" can't work in the previous case
i just want to compare the date part only not the time part..
like in c# i will take the current date as
string today_n = DateTime.Now.ToShortDateString();
which will give only today's date
the query will be like
string query="select *from dbo.param where cvdatetime like '" + today_n + "%'"
what is the correct way?
also i want that whatever be the system date format query should work like even if system date time format is dd-mm-yyyy hh:mm:ss tt the query should work how can i ensure this?
Adding new requirement what if I need to check date hh:mm: only not seconds
i.e, 2014-05-04 12:00: part only not seconds part
You cannot use like as such on datetime column.
Use the below:
select * from dbo.param where convert(varchar, cvdatetime, 120) like '%2014%';
As, far your second question is concerned, you'll have to use parameterized queries to avoid sql injection attacks.
Using SQL Server 2005 or later, just convert the datetime to date:
select *
from dbo.param
where cast(cvdatetime as date) = '2014-05-03';
Do not think about dates as strings. Think of them as dates, with the string format only used for output purposes. Or, if you have to make an analogy to another type, think numbers. As an example, go into Excel, put a date into a cell. Nicely format it. Then set another cell equal to the value of the first cell (=A1 for example). Format that as a number and you will see some strange number, probably in the range of about 40,000. Excel stores dates as number of days since 1970-01-01. SQL has a similar (but different) storage mechanism.
You can use the following for the current date:
SELECT *
FROM dbo.param
WHERE CONVERT(DATE, cvdatetime) = CONVERT(DATE, GETDATE())

Insert and select date from SQL Server database

I have got the following exception when try to select data from SQL Server or inserting data in in with a C# windows application. I am passing the date in where clause of select query in single quotes like this '16/03/2011' The exception message is shown below:
The conversion of a char data type to
a datetime data type resulted in an
out-of-range datetime value.
Is there any perfect solution for inserting and selecting date from sqlserver database irrelevant to the operating system. i.e. that works on both Italian and English OS.
If you can't use stored procs, or parameterized queries, you might want to format the date in a yyyy-mm-dd format. Ex. '2011-03-16'
T-SQL SAMPLE
INSERT INTO MyTable (SomeDate) VALUES ('2011-03-16')
or
SELECT * FROM MyTable WHERE SomeDate <= '2011-03-16'
Also, keep in mind the time portion of the date. If time is not important, then make sure you don't store it, because it could impact your SELECT queries down the road.
Use stored procedures, or parameterized queries. These will let you pass in a C# datetime object, and the conversion will be handled automatically for you.
I would suggest starting with the SQLDataAdapter class. A simple example of this would be:
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable WHERE myDate = #myDate", someSqlConnection)
{
da.SelectCommand.Paramaters.Add("#myDate", new DateTime());
DataTable dt = new DataTable();
da.Fill(dt);
}
However, be aware that there are many different ways of achieving your goal. From your question, I would imagine you are creating SQL strings and executing them against your database. This is considered a Bad Practice for lots of reasons (including the one you describe). Read up about ORMs such as Entity Framework or NHibernate.

Update difficulty in .NET

Update can't work.
sqlstr ="UPDATE emp SET bDate='"+Convert.ToDateTime(txtbDate.Text)+"'";
can't update emp table.
I tried also using Parse method.
It throws error message :
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated.
You should allways use sql parameters when accepting input from a user. This will probably solve your problem as well as increasing security. Try this:
sqlstr ="UPDATE emp SET bDate=#bDate";
SqlCommand.Parameters.AddWithValue("#bDate", Convert.ToDateTime(txtbDate.Text));
Don't use adhoc SQL like this, use parameterised SQL:
sqlstr = "UPDATE emp SET bDate=#NewDate WHERE...."
Then on your SqlCommand, add the #NewDate parameter:
YourSqlCommand.Parameters.Add("#NewDate", SqlDbType.DateTime);
YourSqlCommand.Parameters["#NewDate"].Value = Convert.ToDateTime(txtbDate.Text);
You can use parameterised stored procedures.
The .net datetime contains more values than the SQL DateTime, so thus the out of range error.
Parameterised stored procs also provide more security against sql injection attacks.
You can kill 2 birds with one stone and use a parameter:
UPDATE emp SET bDate=#newDate
And fill the parameter value with a Date directly, using DateTime.Parse() to do the conversion. This also eliminates the SQl injection problem you have now.
have you tried to parse the date value to SQL format(yyyy-MM-dd), ex 2000-12-31
Convert.ToDateTime(txtbDate.Text).ToString("yyyy-MM-dd");
Cheers.
use Parameters to pass the date to the query
this if you are using ole db:
sqlstr = "UPDATE emp SET bDate=? "
command.Parameters.Add(New OleDbParameter("#bDate", Convert.ToDateTime(txtbDate.Text)))
"The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value. The statement has been terminated."
You're date-time is not in the range accepted by the SQL DateTime. What date are you trying to parse? I've this error for some really early dates (1/15/103 for example). Dates are stored in ticks from an arbitrary start point.
The start point for .net is 1/1/0001
The start point for SQL is 1/1/1753
I'm not sure about end values. Try running these and compare. Either code trace, or console writeline.
DateTime netDate = DateTime.MinValue;
SqlDateTime sqlDate = SqlDateTime.MinValue;
DateTime netMaxDate = DateTime.MaxValue;
SqlDateTime sqlMaxDate = SqlDateTime.MaxValue;
Read what everyone else said about parameterizing queries.
it should be plain string because you store it in a sqlstr ;)

Categories