where clause in select statement - datetime issues - sql

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

Related

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.

Access query compare datetime to year only date?

I have the following SQL query in my Access database, connected to SQL Server 2008:
SELECT COUNT(*) as mCount
FROM [Projects]
WHERE [DateProjectSubmitted]>'2014';
This works great and accomplishes exactly what I need.
However, I cannot seem to adapt the query for work within Access within a function I have (all error handling removed):
Public Function getNumberOfYearToDateProjects() As Integer
Dim rsMyRecordSet As ADODB.Recordset
Dim sSql As String
Set rsMyRecordSet = New ADODB.Recordset
sSql = "SELECT COUNT(*) as mCount FROM [Projects] WHERE [DateProjectSubmitted]>#" & Format(Date, "YYYY") & "#"
rsMyRecordSet.Open sSql, CurrentProject.Connection
getNumberOfYearToDateProjects = rsMyRecordSet.Fields("mCount")
End Function
I know Access wants # symbols in the date expression but I cannot seem to make it recognize 2014 as a date for purposes of comparison.
If I copy the SQL directly, I run into problems with data mismatches.
I could do the following, but this just seems ugly
sSql = "SELECT COUNT(*) as mCount FROM [Projects] WHERE [DateProjectSubmitted]>#" & DateSerial(Year(Date), 1, 1) & "#"
Can I modify the SQL query or do I need to use something like DateSerial to create a fake 2014-01-01 date for the comparison?
Assuming that DateProjectSubmitted is a date field, and yourYear is a number
SELECT COUNT(*) as mCount FROM [Projects] WHERE YEAR([DateProjectSubmitted]) > " & yourYear

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)

VB.NET 2012 : Select rows from DataView querying with 'Date'

I have a table which contains a date column called PurchaseDate
I have a list box which displays the months. When I click a month , I need to query the dataSource and collect the rows which have the purchase date in the SelectedMonth.
dv2 = New DataView(ds.Tables(0), "PurchaseDate LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
This code is not working. Because here PurchaseDate is in Date format like 'MM/DD/YYYY'. I think I need to convert the date into string before using LIKE operator. I also tried using as below. Even then, it didn't go fine.
dv1 = New DataView(ds.Tables(0), "convert(varchar2(20),PurchaseDate,103) LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
Here SelectedMonth will be a string like '01', '10'..
Use Linq to avoid such issues:
Dim selectedMonth = Int32.Parse(lbMonth.Text)
Dim filteredRows = From r In ds.Tables(0)
Where r.Field(Of Date)("PurchaseDate").Month = selectedMonth
' if you need a new DataTable
Dim tblFiltered = filteredRows.CopyToDataTable()
You don't say what database you are using, so these are the culture independent date literals that I use in the same scenario...
Oracle
TO_DATE('18-Dec-2012','dd-Mon-yyyy')
SQL/Server
'18-Dec-2012'
Ms/Access (not culture independent, but it's the only thing MS/Access accepts)
#12/18/2012#
So you might format your SQL to say something like this...
PurchaseDate BETWEEN '1-Dec-2012' AND '31-Dec-2012'

Vb.net grabbing time from sql server and formatting it wrong

I run this command in vb
select tuid, finish_time, bay
from orders_table
where tuid between 1001 and 1005 order by finish_time asc
which returns
tuid finish_time bay
1005 2011-10-14 00:20:00.000 5
then I run this command in vb
While commander.Read()
str = "update orders_table set start_time = (" & commander("finish_time") & ") where orders_table.tuid =" & num & ""
Dim myCommand3 As SqlCommand = New SqlCommand(str, myConn2)
myCommand3.ExecuteNonQuery()
When I do the debugger to see what str is sending to the database I get this
str "update orders_table set start_time = (10/14/2011 12:20:00 AM) where orders_table.tuid =1006" String
It throws an error saying incorrect syntax near "12"
It formatting datetime and I don't want it to... how can i fix it so it looks like this
2011-10-14 00:20:00.000
Here is a safe and working version of your current code:
str = "UPDATE orders_table SET start_time = #start_time WHERE orders_table.tuid = #num"
Dim myCommand3 As New SqlCommand(str, myConn2)
myCommand3.Parameters.Add("#start_time", SqlDbType.DateTime)
myCommand3.Parameters.Add("#num", SqlDbType.Int)
While commander.Read()
myCommand3.Parameters(0).Value = commander("finish_time")
myCommand3.Parameters(1).Value = num
myCommand3.ExecuteNonQuery()
End While
But an even better way is to re-write your sql so that it all happens on the server, and you never even read the your select results back to client code. You can write that all in one sql statement.
Instead of () you can use ' or # to delimit the DateTime:
str = "update orders_table set start_time = '" & commander("finish_time") & "' where orders_table.tuid =" & num & ""
This is not the recommended way of using SQL, however (string concatenation), as it opens your code up to SQL Injection.
It is much better to use parameterized queries, this will avoid the whole issue of escaping the values as well. See the answer #JoelCoehoorn gave.
you are formating the string with this (I assume this!)
commander("finish_time")
Just don't format it, or format it like in the database, but the difference lies in how you format it..