How can I convert my strings into a date or datetime datatype in vb.net?
These are my strings that are date and time with this format:
Dim sDate,sTime String
Dim myDate,myTime,dateToSave as Date
sDate = '11/25/13'
sTime = '16:30:05'
I wanted to convert it to a date with this expected output:
myDate = '11/25/2013'
myTime = '16:30:05'
dateToSave = '11/25/2013 16:30:05'
How can I do this so that I can save it to sql table with datatype of datetime?
Declare myDate, myTime and dateToSave as DateTime. Then you can use DateTime.TryParse or DateTime.TryParseExact to convert a string into a DateTime.
PS: I'm reading the sql-server tag in your question. Please remember to pass the values to the database server using parameterized queries - this will save you the next question about how to insert dates and times into the database.
Something as simple as myDate = CDate(sDate & " " & sTime) will work. But also, if you're going to insert or update a SQL Server table that has a column with one of the date/time data types, you can just insert the value as is and it will be stored with the proper data type:
String.Format("INSERT INTO MyTable (MyDateColumn) VALUES({0})", dDateToSave)
dim QueryString as string = "Update someTable set someDate = '" & sDate & " " & sTime & "'"
or
dim datetosave as string = sDate & " " & sTime
dim QueryString as string = "Update someTable set someDate = '" & dateToSave & "'"
Related
The function below is trying to get the earliest date from a table with 3 dates, one for each type of user, care, sales and manager. This is to build up the diary system by first finding the first date in the diary dates. It's working for some users, but in one case the values do not return at and it gives null.
Private Function GetEarliestDate() As Date
Dim strSQL As String
Dim cmd As New SqlCommand
Dim dDate As Date
Try
strSQL = "Select dT.RecordID, MIN(dT.inDate) As [EarliestDate]
FROM (
Select RecordID, SentDate As [inDate]
From tblOrderDetails Where Flagged = 0 AND SalesID = '" & gUserID & "'
UNION ALL
Select RecordID, DiaryDate AS [inDate]
From tblOrderDetails
Where Flagged=0 And ManID ='" & gUserID & "'
UNION ALL
Select RecordID, CareDate As [inDate]
From tblOrderDetails
Where Flagged = 0 And CareID ='" & gUserID & "'
) As dT Group By RecordID"
cmd.CommandText = strSQL
cmd.Connection = CnMaster
cmd.CommandType = CommandType.Text
Dim RecordCount As Integer
RecordCount = 0
dDate = DateTime.MaxValue
Using reader As SqlDataReader = cmd.ExecuteReader()
While (reader.Read())
RecordCount += 1
Dim dt As DateTime = reader.GetDateTime(1)
If dt < dDate Then
dDate = dt
End If
End While
If dDate = DateTime.MaxValue Then
dDate = DateTime.MinValue
End If
End Using
cmd.Dispose()
Return dDate
Catch ex As Exception
Error_Handler(ex, "GetEarliestDate", "Unable to Get The Earliest Date!")
End Try
Put in all 3 queries additional where:
where SentDate is not null ...
where DiaryDate is not null ...
where CareDate is not null ...
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
I am trying to get a form setup to launch various reports based on different criteria and I am having problems getting one of the reports that is a GroupBy/Count/Sum based SQL Data source to work between 2 unbound textboxes serving as a FromDate and a ToDate.
VBA script - calling report from form (frmRptFeedback):
Private Sub cmdPrint_Click()
If Not chkPrintPreview Then
Set Application.Printer = Application.Printers.Item(cboPrinter.Value)
End If
Dim strCondition As String
Dim strFromDate As String
Dim strToDate As String
strFromDate = txtFromDate.Value
strToDate = txtToDate.Value
Select Case opgOptions
Case 1 ' Feedback By Employee
If IsNull(cboEmployee.Value) Then
strCondition = "DateSubmitted BETWEEN '" & strFromDate & "' AND '" & strToDate & "'"
Else
strCondition = "RespEmp = '" & cboEmployee.Value & "' AND DateSubmitted BETWEEN '" & _
strFromDate & "' AND '" & strToDate & "'"
End If
Call OpenReport("rptFeedbackByEmp", IIf(chkPrintPreview, acViewPreview, acViewNormal), strCondition)
Case 2 ' Feedback By Team
If IsNull(cboTeam.Value) Then
strCondition = "DateSubmitted BETWEEN '" & strFromDate & "' AND '" & strToDate & "'"
Else
strCondition = "EmpType = '" & cboTeam.Value & "' AND DateSubmitted BETWEEN '" & _
strFromDate & "' AND '" & strToDate & "'"
End If
Call OpenReport("rptFeedbackByTeam", IIf(chkPrintPreview, acViewPreview, acViewNormal), strCondition)
Case 3 ' Feedback By Project #
If IsNull(txtProjectID) Then
strCondition = "DateSubmitted BETWEEN '" & strFromDate & "' AND '" & strToDate & "'"
Else
strCondition = "ProjectID = " & txtProjectID & "AND DateSubmitted BETWEEN '" & _
strFromDate & "' AND '" & strToDate & "'"
End If
Call OpenReport("rptFeedbackByProject", IIf(chkPrintPreview, acViewPreview, acViewNormal), strCondition)
End Select
If Not chkPreview Then
Set Application.Printer = Nothing
End If
End Sub
SQL query - initially pulling data into main SQL View (vueRptFeedback):
SELECT f.FeedbackID, f.BFID, bf.ProjectID, p.ProjectName, e2.Name AS PM, e1.Name AS RespEmp,
et.Description AS EmpType, f.SubByInits, f.DateSubmitted, f.QtyIssues,
f.EstHoursImpact, f.PlusDelta, f.Notes, f.HowResolved
FROM dbo.tblEmployee e2
INNER JOIN dbo.tblProject p
INNER JOIN dbo.tblBookingForm bf
ON p.ProjectID = bf.ProjectID
ON e2.EmployeeID = p.Scope_PM_EmployeeID
RIGHT OUTER JOIN dbo.tblEmployeeType et
INNER JOIN dbo.tblEmployee e1
ON et.EmployeeTypeID = e1.EmployeeTypeID
INNER JOIN dbo.tblFeedback f
ON e1.EmployeeID = f.ResponsibleEmpID
ON bf.BookingFormID = f.BFID
SQL query - current recordsource for report by Project ID (vueRptFeedbackByProject):
SELECT ProjectID, ProjectName, RespEmp, COUNT(FeedbackID) AS CountReports,
SUM(QtyIssues) AS SumIssues, SUM(EstHoursImpact) AS SumHours
FROM vueRptFeedback
WHERE (DateSubmitted
BETWEEN CONVERT(DATETIME, [Forms]![frmRptFeedback]![txtFromDate], 102)
AND CONVERT(DATETIME, [Forms]![frmRptFeedback]![txtToDate], 102))
GROUP BY ProjectID, RespEmp, ProjectName, DateSubmitted
ORDER BY ProjectID, RespEmp
I know my problem is in the WHERE clause as when I take it out, the report pulls fine but with all records, not the ones between those two dates. Once I can get the report to pull between the txtFromDate and txtToDate, I will probably need to change the OpenReport() to pass the txtFromDate and txtToDate as parameters instead of a Between X and Y, but I keep getting tripped up by syntax on the Recordsource of the report.
Fundamentally, you are conflating two SQL dialects - SQL Server SQL and MS Access SQL. There is no CONVERT() function in Access SQL syntax which appears to be the engine running the recordsource of the report and not the pass-through query, vueRptFeedback, run by MSSQL.
Consider using FORMAT() to align dates to ANSI datetime format: YYYY-MM-DD:
SELECT ProjectID, ProjectName, RespEmp, COUNT(FeedbackID) AS CountReports,
SUM(QtyIssues) AS SumIssues, SUM(EstHoursImpact) AS SumHours
FROM vueRptFeedback
WHERE (DateSubmitted
BETWEEN FORMAT([Forms]![frmRptFeedback]![txtFromDate], "YYYY-MM-DD")
AND FORMAT([Forms]![frmRptFeedback]![txtToDate], "YYYY-MM-DD"))
GROUP BY ProjectID, RespEmp, ProjectName, DateSubmitted
ORDER BY ProjectID, RespEmp
On the VBA side, you can still use Format() as many of Access's SQL functions derived from VBA functions (possibly, this is the reason Access SQL differs from its other RDMS counterparts who adhere to ANSI more due to the need to stay compatible in MS Office VBA context):
Dim strFromDate As String
Dim strToDate As String
strFromDate = Format(txtFromDate.Value, "YYYY-MM-DD")
strToDate = Format(txtToDate.Value, "YYYY-MM-DD")
...
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
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";