I'm trying to query my database with ADO.NET
string con = "Data Source=xx.xx.xx.xx\\SqlExpress;Network Library=DBMSSOCN; Initial Catalog=DB;User ID=ID;Password=xxxxx;";
SqlConnection connection = new SqlConnection(con);
using (connection)
{
string query = "SELECT * FROM Gigs where Date >= GetDate()";
SqlCommand command = new SqlCommand(query, connection);
var da = new SqlDataAdapter();
connection.Open();
SqlDataReader reader = command.ExecuteReader();
da.SelectCommand = command;
connection.Close();
var ds = new DataSet();
da.Fill(ds);
gigs.DataSource = ds;
gigs.DataBind();
}
The code executes fine, but it shows incorrect values. I was expecting to see only dates after today. Yet, I see values from the past and future. It's as if the query is simply SELECT * from Gigs
In SQL Server, the column Date is of type date.
What have I done wrong?
A correct way to get rows from tomorrow and forward :
SELECT * FROM Gigs
WHERE [Date] >= CAST(getdate() + 1 as date)
This would also work
[Date] >= DATEADD(d, datediff(d, 0,getdate()),1)
Using DATEDIFF will make the expression non-sargable, resulting in bad performance.
string query = "SELECT * FROM Gigs WHERE CONVERT(VARCHAR(10), #date, 111) > CONVERT(VARCHAR(10), GETDATE(),111)"
Use DATEDIFF.
Change your string query as follows.
string query = "SELECT * FROM Gigs where DATEDIFF(day, GETDATE(), [Date]) > 0";
This will select the rows which the Date column is newer than today's date.
Related
I have the below query and I was wondering how to setup an ODBC connection to get this to an excel spreadsheet.
declare #StartDate DATE
declare #EndDate DATE
SELECT Sum(case when status = 6 then 1 else 0 end) as Failed,
Sum(case when status = 9 then 1 else 0 end) as Successful,
UniqueID
Into #tempsheet1
FROM Documents
WHERE ownerID = 467
and status in (6,9)
and CreationTime between #StartDate and #EndDate
Group By UniqueID
Select D.UniqueID, FromName, ToName, CreationTime,
cast(CreationTime as date) as CreationDate, cast(CreationTime as date) as CreationTime,
ErrorCode, ElapsedSendTime, RemoteID
From #tempsheet1 ts1
Inner Join Documents D On
D.UniqueID = ts1.UniqueID
and [Status] = 9
ORDER BY D.CreationTime desc
I'm still researching stuff online, but if anyone can point me in the right direction or give me some tips that would be awesome.
In excel go to Data tab > Get external data > From other sources > From Microsoft Query. From there depends on what type of database you are connecting to but the wizard should guide you through.
Once you have your connection set you can right click in the resulting data set and select table > edit query, choose command type = SQL and then edit your query as required.
Depending on what you are doing an ADO db connection may be better and will allow you to set dynamic date filters and the like... but that is another topic
Edit: ADO approach below
Add a reference to Microsoft ActiveX Data objects library
Figure out your connection string: https://www.connectionstrings.com/
Implement something like the below
.
Sub adoConExample()
Dim startDate As String
Dim endDate As String
Dim con As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sql As String
Set con = New ADODB.Connection
Set rs = New ADODB.Recordset
startDate = format("Your date range reference".value, "yyyy-mm-dd")
endDate = format("Your date range reference".value, "yyyy-mm-dd")
With con
.ConnectionString = "Your connection string"
.CursorLocation = adUseClient
.Open
End With
sql = "Your sql string"
sql = Replace(sql, "DATE1", startDate)
sql = Replace(sql, "DATE2", endDate)
rs.CursorLocation = adUseClient
rs.Open sql, con, adOpenStatic, adLockReadOnly, adCmdText
"Your paste target range".CopyFromRecordset rs
con.Close
rs = Nothing
con = Nothing
End Sub
if i click the search button, i keep on receiving an error at the value of IDNo, incorrect syntax near '11111' can someone help me?
With acc
IDNo = .IDNo
StartDate = DateTime.Parse(.StartDate).ToString("M/d/yyyy")
EndDate = DateTime.Parse(.EndDate).ToString("M/d/yyyy")
ProjectName = .ProjectName
ReferenceNo = .ReferenceNo
TaskCode = .TaskCode
FileName = .Filename
End With
dgAccomplishment.DataSource = Nothing
dgAccomplishmentPT.DataSource = Nothing
da = New SqlDataAdapter("dbo.process_time #User='" & IDNo & "' ,#From='" & StartDate & "',#To='" & EndDate & " 11:59:59 PM'", DB.GetConnection)
dt = New DataTable
da.Fill(dt)
dgAccomplishment.DataSource = dt
dgAccomplishment.Columns("ID").Visible = False
dgAccomplishment.Columns("TimeSave").Visible = False
da.Dispose()
dt.Dispose()
this is my stored procedure
SELECT a.ID, RTRIM(a.Last_User) [ID No.],
RTRIM(Users.FIRSTNAME + ' ' + Users.INITIAL + '. ' + Users.LASTNAME) [Name],
RTRIM(a.ProjectName) [Project Name],
a.ProjectNo, a.ProjectCode,
RTRIM(a.Filename) [Filename],
RTRIM(a.Filesize) [Filesize],
RTRIM(a.filesizeunit) [FileSizeUnit],
a.TimeSave [TimeSave]
from DBase.dbo.Acc a
INNER JOIN dbo.Users ON a.Last_User = Users.IDNo
WHERE a.Last_User in (#user)
and CONVERT(VARCHAR(10),timesave,101) BETWEEN #From AND #To
ORDER BY RTRIM(a.SubGroup), RTRIM(a.Last_User)
but when i try to run the procedure in a query it works well.
Because you are using string concatenation, you have the age old single quote problem: If IDNo value contains a single quote, then your query will fail.
What's worse, your code is susceptible to sql injection attacks.
You have to escape ALL parameters for single quotes, replacing them by 2 single quotes.
Best solution here: use parametrized sql
What is the correct Date Format should I use in MS SQL Server if I have this kind of scenario?
--This values here will be supplied by a datetimepicker Control
#StartDate = '05/15/2013 10:00 PM'
#EndDate = '05/16/2013 06:00 AM'
SELECT *
FROM tblSomething
WHERE TransDate >= #StartDate AND TransDate <= #EndDate
How can I format the TransDate field?
Is this Correct?
Declare #StartDate as datetime
Declare #EndDate as datetime
set #StartDate = '05/15/2013 10:00 PM'
set #EndDate = '05/16/2013 06:00 AM'
Select * from tblSomething Where convert(varchar(20),TransDate,100) >= convert(varchar(20),#StartDate,100) and convert(varchar(20),TransDate,100) <= convert(varchar(20),#EndDate,100)
The reason AM/PM is important to me is because we have employees that have transactions that starts 10PM in the evening and ends at 6am the next morning. I need to extract the transactions of that employee with that time frame.
If you need to think about date formats at all, you're doing it wrong.
The DateTimePicker control gives you a value of the .Net DateTime type. Your TransDate column should be a Sql Server DateTime type, as should your #StartDate and #EndDate parameters. At no point should you ever need to express any of these as a string. They should always be a binary format that isn't even human readable. If you've done this, the select query as written should do what you need.
Here's an example (C#, can do VB if you'd prefer) of how all this might work:
//imaginary function to check if there's at least one record in the data range
bool CheckDates(DateTime startDate, DateTime endDate)
{
//sql is unchanged from your question
string sql = "Select * from tblSomething Where TransDate >= #StartDate AND TransDate <= #EndDate";
using (var cn = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql))
{
cmd.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = endDate;
cn.Open()
using (SqlDataReader rdr = cmd.ExecuteReader())
{
//all we care is whether there's at least one row
// there is a row if and only if .Read() succeeds
return rdr.Read();
}
}
}
You could call it like this:
//hopefully you picked better control names :)
if (CheckDates(dateTimePicker1.Value, dateTimePicker2.Value))
{
//do something
}
The important thing is that at no point anywhere do you ever convert that DateTime to a string.
I am trying to read the data from a database and pass the dates that have been selected from a datetime picker as values for the query. I keep getting all kind of error messages that are becouse of the wrong data type, i think.
What am i doing wrong here??
Please help.
P
private void buttonRetrieveData_Click(object sender, EventArgs e)
{
openConnection();
//TODO: Add function te retrieve data between dates enteren in datetimepickers
DateTime datumVan = dateTimePickerVan.Value;
DateTime datumTot = dateTimePickerTot.Value;
string query = "select * from my_Table where date between '" + datumVan.ToShortDateString() + "' and '" + datumTot.ToShortDateString() + "' order by date desc";
DataSet dset = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
SqlCommandBuilder cb = new SqlCommandBuilder(adapter);
adapter.Fill(dset, "my_Table");
dataGridView1.DataSource = dset;
dataGridView1.DataMember = "my_table";
adapter.Update(dset, "my_Table");
closeConnection();
}
I know that the SQL datetime type has a date range from : January 1, 1753, through December 31, 9999
And .NET datetime min value is 00:00:00.0000000, January 1, 0001.
I would recommend you to check that you are not falling between ranges.
That means that if your datetime picker is not initiated with SQL min value it might return an invalid SQL date.
Don't treat dates as strings. It's as simple as that, avoid converting them to strings in the first place, and you save yourself a whole heap of trouble.
So, instead of:
string query = "select * from my_Table where date between '" + datumVan.ToShortDateString() + "' and '" + datumTot.ToShortDateString() + "' order by date desc";
Have instead:
string query = "select * from my_Table where date between #Van and #Tot order by date desc";
And then add parameters to the command object:
adapter.SelectCommand.Parameters.AddWithValue("#Van",datumVan);
adapter.SelectCommand.Parameters.AddWithValue("#Tot",datumTot);
Let ADO.Net and SQL Server deal with the issue of translating .NET datetime values into SQL Server datetime values.
I faced a similar problem but my fix was simple:
Instead of
+ datumVan.ToShortDateString() + "' and '" + datumTot.ToShortDateString() +
I changed to
+ datumTot.ToShortDateString() + "' and '" + datumVan.ToShortDateString() +
Give it a try, if this helps.
Also, is your date is getting converted to string by use of ToShortDateString() but what format is that of your date in table ??
May be you can try following query as well:
select * from my_Table where CAST(date AS DATE) between CAST('" + ToShortDateString() + "' AS DATE) and CAST('" + datumTot.ToShortDateString() + "' AS DATE) order by date desc";
I need your help to figure out and maybe solve this problem.
I have a DataReader and when use the function GetDateTime, to read a Date column, I get the min value. I don't see a GetDate function. I tried changing the datatype of the column to Datetime, in order to both have the same datatype, but it's the same result.
This is the definition of the table:
CREATE TABLE [dbo].[Solped](
[docNumber] [int] NOT NULL,
[docType] [nvarchar](255) NOT NULL,
[createDate] [date] NULL,
[hora] [time](2) NULL,
....
This is where I read the database:
string sql = "SELECT * FROM Solped order by docNumber DESC";
System.Console.WriteLine(sql);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
solped = new Solped();
solped.docNumber = reader.GetInt32(0);
solped.docType = reader.GetString(1);
DateTime dt = reader.GetDateTime(2);
solped.fecha = dt;
This is the value presented when debbuging:
dt = {1/1/0001 12:00:00 AM}
And this is the presented value in the program:
Date(1345089600000)
I am totally confused about that I don't know what function or actions should I take to solve the problem. If you may help, I would greatly appreciate that. Thanks!
Look like you have the date and the time in two different columns in your table, try this
SELECT DocNumber, DocType,
CAST(CAST(createDate as varchar(10)) + ' ' + CAST(hora as varchar(12)) as datetime) as fullDate
FROM Solped