Click here to Skip to main content
15,900,973 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have error The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. in cmd.executescalar()



VB
Public Function checkDate(ByVal tbl As String, ByVal AppId As Double, ByVal col As String, ByVal val As String) As Boolean
            If con.State = ConnectionState.Open Then
                con.Close()
            End If
            Dim valdate As Date = Convert.ToDateTime(val)
            MsgBox(valdate)

            Dim i As Integer

            'databaseConnection(cmd)

            Dim cmd As New SqlCommand("select count(*) from " & tbl & " where appid=" & AppId & " and " & col & "<='" & valdate & "'", con)


            'cmd.CommandText = "select count(*) from " & tbl & " where appid=" & AppId & " and " & col & "<='" & valdate & "'"
            'cmd.CommandType = CommandType.Text
            MsgBox(cmd.CommandText)

            con.Open()
            i = cmd.ExecuteScalar()


            MsgBox(i)
            ' Convert.ToInt32(i)


            If (i > 0) Then
                Return True
            Else
                Return False
            End If
            con.Close()

        End Function
Posted
Updated 7-Aug-15 4:27am
v2
Comments

Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.

Then, convert your val to a DateTime instead of passing a string - and check it in your VB code to make sure the user entered a valid value - and pass the DateTime directly to SQL.

The advantage of this - apart from your database not being deleted by a malicious user - is that you have access to the user locale when you do the conversion, so you can generate the correct date from his entry. SQL can't do that, because it doesn't know if the user wanted US MM/dd/yy, European dd/MM/yy, or ISO yy/MM/dd format - so it has to guess.
 
Share this answer
 
DateTime type in t-sql has a limited range. Consider using DateTime2 instead.

DateTime:
Min: 1753-01-01 00:00:00.000
Max: 9999-12-31 23:59:59.997

DateTime2:
Min: 0001-01-01 00:00:00.0000000
Max: 9999-12-31 23:59:59.9999999

Good luck!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900