ADO - Different Date Formats in VB and SQL - sql

Im executing this query in VB:
Dim str As String = "select date_created from TABLE_DATES group by date_created"
Dim cm As SqlCommand = New SqlCommand(str, cn)
..
It's returning the following field in VB:
'11/7/2013 4:30:44 PM'
While in SQL the same field is:
'2013-11-07 16:30:44.917'
So when I send the date from VB to SQL in a query condition, SQL doesn't find the row I asked for.
Any solution to this?

See my answer to another question that will help you ensure your date is always in the correct format. What you do with it, is your decision.

Related

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.

search for a field between two dates in vb.net

My information in database is weak and I do not know how to use queries. I have searched the web and I learned few thing about making queries and I found an example but i do not know how to use it in vb.net.
The query in SQL server will be like this:
select hb from gen where date between 12/6/2014 and 16/6/2014
It works fine, but i don't know how to use it in vb.net
so wrote this line of code and i think my solution will be something like this:
BindingSource1.Filter = String.Format("select hb from gen where date between" & DateTimePicker1.Value & "and" & GENDateTimePicker1.Value)
so what is wrong with this line
If you'd read the documentation then you'd know that the BindingSource.Filter property requires dates to be expressed in the format #M/dd/yyyy#. Also, the String represents just a WHERE clause, not an entire query. You're not using String.Format properly either. Your code should be:
BindingSource1.Filter = String.Format("[Date] BETWEEN #{0:M/dd/yyyy}# AND #{1:M/dd/yyyy}#", DateTimePicker1.Value, GENDateTimePicker1.Value)
Here is an example on how to use your sql query in vb.net:
First, you want to setup your connection string to your database. Next, you can declare a string with the contents of your sql statement. Third, you'll want to setup a using statement that will close the sql connection when it exits. I would also read up on parameterized sql to mitigate attacks on your database.
Dim con As String = (ConfigurationManager.ConnectionStrings("YOURCONNECTIONSTRINGNAME").ConnectionString)
Dim result as String = String.Empty 'set the result to whatever the datatype of hb is in your database
Dim query as String = "select hb from gen where date between '12-6-2014' and '16-6-2014'"
Using conn As New SqlClient.SqlConnection(con)
Try
conn.Open()
Dim command As New SqlClient.SqlCommand(query, conn)
command.Connection = conn
command.CommandType = CommandType.Text
result = command.ExecuteScalar()
conn.Close()
conn.Dispose()
Catch ex As Exception
System.Diagnostics.Debug.WriteLine(ex.Message)
End Try
End Using
this is the solution which i made after hard searching and a lot of lectures in vb.net and SQL server "Excuse me I am a beginner"
Me.BindingSource1.Filter = String.Format(" date <= #{0:M/dd/yyyy}# AND Date >= #{1:M/dd/yyyy}# and hb like'" & TextBox1.Text & "%'", DateTimePicker1.Value, DateTimePicker2.Value)
and "hb" is the name of the field which i want to find
thank you for your time and the fast respond

Dataset from SQL Query Won't Return Time of 00:00

I am working on a web application in VB.net 2008 with a SQL 2008R2 database on the back end. I am sending a query to SQL through VB to obtain a patient's hospital visit information:
SELECT TOP 1 * FROM visit WITH (NOLOCK) WHERE visit_code = '123' AND start_date <= '07/17/2012' ORDER BY visit_code DESC, start_date DESC
This returns the correct record. However, there is a hold_start_date_time field defined as datetime in the database which contains both the date and time. Everything works great unless the time is midnight - 00:00.
When I run the above query directly in SQL Server Management Studio the field displays correctly. But in the dataset in VB.NET when I look at the datarow the field has only the date with no time at all. A time of anything other than 00:00 populates the dataset correctly.
Unfortunately, midnight is a perfectly valid time for this field. Is there a way I can get it to appear in the dataset?
Dim dsData as DataSet
dsData = GetDataSet(strSql, "visit")
If DataSetRowCount(dsData, "visit") > 0 Then
Dim drData As DataRow
drData = dsData.Tables("visit").Rows(0)
End If
Public Overloads Function GetDataSet(ByVal strSQL As String, ByVal srcTable As String) As DataSet
Dim daData As SqlDataAdapter
daData = New SqlDataAdapter(strSQL, strConnectionString)
daData.Fill(dsData, srcTable)
daData.Dispose()
daData = Nothing
Return dsData
End Function
Any help would be much appreciated.
I guess that the time is there, just not showing up because the visualizer tool (VS Debugger?) don't show if it's 00:00. Try dump in the HTML or window with proper formatting and you will be fine.

How to get column names for a linq sql query result in vb 2010

I've seen C# examples but can not find a way to get the column names from the results of a LINQ SQL query in VISUAL BASIC.
So myLINQ query looks like this:
Dim dbs As New DataClasses1DataContext
Dim s As Table(Of sched) = dbs.GetTable(Of sched)()
Dim sQuery = From sp In s
Where sp.custID = cID
Select sp Order By sp.scheddate
There are 13 fields in the table sched, and I'd like to be able to read off the column names in a foreach type loop. Can anyone help me?

sql from vb cannot convert to date

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)