sql from vb cannot convert to date - sql

Hi i'm trying to convert this line to get list of people active over todays date but cannot get it to work
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where convert(varchar,convert(datetime,replace('" & DateTimeUgovora.Value.ToString & "','#','')),111) >= convert(varchar,getdate(),111)", myConn)
error is conversion of varchar data type to a datetime data type resulted in an out-of-range value.
my string that I get from front is
"29.11.2013. 19:41:08"
I searched everywhere and cannot find the answer please help

You should not need to convert the datetime value to a string, because in SQL you can compare datetime values directly. This is much more stable as it doesn't depend on locale settings. I don't fully understand your SELECT clause as even if the comparison works, it will return either all the rows in the table or none.
However, if you want to use the table column Kli_Ugovor_do in your comparison, you can change your statement to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= getdate()", myConn)
Btw: in your statement you included the value of the combobox by string concatenation. You should get used to including parameters in your statements in order to avoid SQL injection attacks.
So if you want to use the value of the DateTimePicker, your code should look similar to this:
adapter.SelectCommand = New SqlCommand( _
"select * from klijent where Kli_Ugovor_do >= #dt", myConn)
adapter.SelectCommand.Parameters.AddWithValue("#dt", dateTimeUgovora.Value)

I just created a quick console application with the string mention by you. This may be helpful.
Imports System.Globalization
Module Module1
Sub Main()
Dim myDateString As String = "29.11.2013. 19:41:08"
myDateString = myDateString.Replace(".", "")
Dim myDate As DateTime = DateTime.ParseExact(myDateString, "ddMMyyyy HH:mm:ss", CultureInfo.InvariantCulture)
Console.WriteLine(myDate.ToString())
Console.ReadLine()
End Sub
End Module
I created a quick module for tsql as well, maybe it will help:
Declare #dt varchar(20)
set #dt = '29.11.2013. 19:41:08'
select convert(datetime, Replace(#dt, '. ', ' '), 103)

Related

How to cast DB2 Timestamp to vb.net date?

When I populate my vb.net gridview using DB2 SQL, it displays DB2 Timestamp as:
2020-08-25-14.59.11.000000
^ What's the cleanest way to cast that as a vb.net Date? FWIW, this works:
Dim mydate As Date = CDate("2020-08-25 14:59:11.000000")
But, the colons in 14:59:11 do not exist, the string I'm working with has 14.59.11
Any help greatly appreciated.
Edit:
As requested,
screenshot of what data looks like when queried in AS400
Edit2:
Dim strSelect As String = "" &
"SELECT SUBMITTIME " &
"FROM MYTABLE " &
"WHERE EFYEAR=" & Now.Year & " AND EFMONTH=" & Now.Month
Dim dt As DataTable = SQL.Get_DataTable(strSelect)
grv.DataSource = dt
grv.DataBind()
Get_DataTable is just using OleDbConnection, OleDbCommand, OleDbDataAdapter, etc to fill a DataTable.
You can't cast something as a type that it isn't. The whole point of casting is that you don't change the object but rather the way you access the object. If you're changing the object then it is a conversion, not a cast.
If you want to convert something then the first step is to know what you're converting from. If you are converting from a String of a known format to a DateTime then you would use Date.ParseExact.
If the data is in a DataTable, add a new column with the appropriate data type, do the conversion in a loop and then, if appropriate, remove the original column.
myDataTable.Columns.Add("DataColumn", GetType(Date))
For Each row As DataRow In myDataTable.Rows
row("DateColumn") = Date.ParseExact(CStr(row("TextColumn")), "yyyy-MM-dd-HH.mm.ss.ffffff", Nothing)
Next
myDataTable.Columns.Remove(myDataTable.Columns("TextColumn"))

Filter between dates VB.NET and Access database

As the title says, I'm unable to filter an SQL sentence from access database with vb.net
Dim data1 As String = DateTimePicker1.Value.ToShortDateString
Dim data2 As String = DateTimePicker2.Value.ToShortDateString
Dim sql As String = "SELECT totais.* From totais Where totais.data Between #" + data1 + "# And #" + data2 + "#;"
It gives me random values. If i put 1-10(October)-2019 it gives me all the records in system, if i put 12-10(October)-2019 it only gives today's record (doesn't show yesterday and before records). I'm not finding the problem, can you please help?
Thanks
I would use Parameters instead of concatenating a string for the Sql statement. It makes the statement much easier to read and avoids syntax errors.
With OleDb the order that parameters appear in the sql statement must match the order they are added to the parameters collection because OleDb pays no attention to the name of the parameter.
Private Sub OPCode()
Dim sql As String = "SELECT * From totais Where data Between #StartDate And #EndDate;"
Using dt As New DataTable
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sql, cn)
cmd.Parameters.Add("#StartDate", OleDbType.Date).Value = DateTimePicker1.Value
cmd.Parameters.Add("#EndDate", OleDbType.Date).Value = DateTimePicker2.Value
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
DataGridView1.DataSource = dt
End Using
End Sub
You need to use single quotes and convert type in SQL like this:
SELECT totais.* FROM totais WHERE totais.data Between CDATE('" + data1 + "') And CDATE('" + data2 + "');"
You should use parameters as per Mary's answer BUT for completeness...
Ms/Access requires dates specified as #mm/dd/yy# so your SQL will only work properly where the local date time format is mm/dd/yy. i.e. mostly the US. Otherwise you will have to format your date string.

VB.NET date format

How do I replace 2014-12-27 with the current date in the statement
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = '2014-12-27'", conn)
or how can I have the date in the format 'yyyy-mm-dd'in the statement
Dim Tday As Date = Date.Today
First, a date has no format, it has only a value. A date-string can have a format.
Second, always use sql-parameters instead of string concatenation if you build your sql query. That prevents sql-injection or conversion/locatization issues. And always pass the correct type(date is this case) instead of letting the database interpret your argument.
Using cmd As New SqlCommand("Select * from LateComersReport where PDate = #PDate", conn)
cmd.Parameters.Add("#PDate" , SqlDbType.Date).Value = Date.Today ' or SqlDbType.DateTime '
' .. '
End Using
You can simply change your SQL query to this:
"Select * from LateComersReport where PDate = CONVERT(DATE, GETDATE())"
A few things I'd like to point out: date variables, whether in SQL or in .NET, do not have formats. Formatting is only useful/relevant when you are talking about displaying a date, i.e. as a string in a report or in a UI. You shouldn't care how a date is displayed when it's a date value being used in your code.
Also, as a habit, you should use parameters in your SQL statements whenever applicable as opposed to concatenating strings together. For example, if you were to insert your own date value in the query instead of using SQL's built-in GETDATE() function, you would do this:
Dim cmd As New SqlCommand("Select * from LateComersReport where PDate = #MyDateValue", conn)
Dim param As New SqlParameter("#MyDateValue", Now)
cmd.Parameters.Add(param)
The reason for this is string concatenation to build SQL is inherently unsafe due to the risk of SQL injection attacks.

Trouble converting DateTime (.net) to datetime (SQL server)

I'm trying to pass a string (from a text file) - '17/07/99' into a sql server table - the destination is a date column.
the insert is in a string, of the form:
Dim cmd As New SqlCommand(...yada...)
cmd.CommandText = "INSERT INTO my.table (thisDate, ...etc... ) VALUES (#myDate, ...etc...)"
I am adding the parameters to the cmd using:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = Date.ParseExact("11/11/11", "dd/MM/yy", CultureInfo("en-GB"))
When I come to ExecuteNonQuery
I get cannot convert string to datetime error.
I thought the ParseExact was doing the conversion from string to DateTime??
Do I really need to do a CONVERT in the sql as well as using datetime structures ?!
Try this:
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = new DateTime(2011, 11, 11);
And also see this:
http://msdn.microsoft.com/en-us/library/w2sa9yss(v=vs.110).aspx
just tested this and it works ... you only need to format your date if you want it consistent no matter what culture your OS is otherwise you don't have to do that
you can use this way
Dim d As Date = "17/07/99"
or you can use this way
Dim d As Date = "17.07.99"
if you only have date without time then it doesn't matter what you use
you can either use this
cmd.Parameters.Add("#myDate", SqlDbType.DateTime).Value = d
or this
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = d
i just tried both versions mixed and no error whatsoever and rows inserted
Try formatting the string before adding it.
Format(YourTimeStringHere, dd-MM-yy)

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using