来自vb的sql无法转换为日期

时间:2013-11-29 18:58:56

标签: sql sql-server vb.net

您好我正在尝试将此行转换为获取今天活跃的人员列表,但无法让其工作

adapter.SelectCommand = New SqlCommand( _
            "select * from klijent where convert(varchar,convert(datetime,replace('" & DateTimeUgovora.Value.ToString & "','#','')),111) >= convert(varchar,getdate(),111)", myConn)

错误是将varchar数据类型转换为导致超出范围值的日期时间数据类型。

我从前面得到的字符串是

“29.11.2013.19:41:08”date problem

我到处搜索,找不到答案请帮忙

2 个答案:

答案 0 :(得分:2)

您不需要将datetime值转换为字符串,因为在SQL中您可以直接比较datetime值。这更加稳定,因为它不依赖于区域设置。我不完全理解你的SELECT子句,因为即使比较有效,它也会返回表中的所有行或者没有。
但是,如果要在比较中使用表格列Kli_Ugovor_do,可以将语句更改为:

adapter.SelectCommand = New SqlCommand( _
            "select * from klijent where Kli_Ugovor_do >= getdate()", myConn)

顺便说一下:在你的陈述中,你通过字符串连接包含了组合框的值。您应该习惯在语句中包含参数,以避免SQL注入攻击。
因此,如果您想使用DateTimePicker的值,您的代码应该类似于:

adapter.SelectCommand = New SqlCommand( _
            "select * from klijent where Kli_Ugovor_do >= @dt", myConn)
adapter.SelectCommand.Parameters.AddWithValue("@dt", dateTimeUgovora.Value)

答案 1 :(得分:0)

我刚刚创建了一个快速控制台应用程序,其中包含了您提到的字符串。这可能会有所帮助。

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

我也为tsql创建了一个快速模块,也许它会有所帮助:

Declare @dt varchar(20)
set @dt = '29.11.2013. 19:41:08'
select convert(datetime, Replace(@dt, '. ', ' '), 103)