C# 在sql查询中使用.net Datetime

C# 在sql查询中使用.net Datetime,c#,.net,sql,vb.net,datetime,C#,.net,Sql,Vb.net,Datetime,我有一个DateTime对象要与where子句中的sql DateTime字段进行比较。我目前正在使用: "where (convert( dateTime, '" & datetimeVariable.ToString & "',103) <= DatetimeField)" “where(convert(dateTime,”&datetimeVariable.ToString&“”,103)不使用字符串连接,使用参数化查询。传入类型为dateTime的参数值。这完全避

我有一个DateTime对象要与where子句中的sql DateTime字段进行比较。我目前正在使用:

"where (convert( dateTime, '" & datetimeVariable.ToString & "',103) <= DatetimeField)"

“where(convert(dateTime,”&datetimeVariable.ToString&“”,103)不使用字符串连接,使用参数化查询。传入类型为
dateTime
的参数值。这完全避免了格式问题,提高了后续查询的性能,并绕过了固有的漏洞(SQL注入)在以这种方式形成SQL时,您可以对其敞开心扉

"where @dateTime <= DateTimeField"

“其中@dateTime参数。始终为参数:

where @someVar <= DatetimeField
where@someVar如果您希望ToString()始终出现,而不考虑区域性,请指定特定的区域性:

    Dim D = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)
    '-or-
    Dim D = DateTime.Now.ToString(New System.Globalization.CultureInfo("en-us"))

应该在问题中提到,我正在对不面向客户的旧代码进行更新,并且不会将整个应用程序(甚至这部分应用程序)转换为使用参数化SQL为什么不使用参数?我正在对不面向客户的旧代码进行更新,即没有时间:(使用参数化查询比使用串联查询花费的时间要少。为什么建议使用ISO日期格式。例如DateTime.Now.ToString(“s”),这应该始终适用于SQL,因为SQL框可能具有不同的区域性?谢谢Chris。(但是)如果您阅读此答案并想,“这就是如何做到的,”阅读其他答案,寻找一种更适合我的方法。@Parmasan,如果你有更好的方法,为什么不在答案中更充分地分享它?@Patrick,我不是100%确定,这就是为什么我对Chris答案背后的推理感兴趣。@Parmasencodie,ISO日期格式也很好,而且实际上更短(因此可能更好),我只是演示如何指定特定的文化。
    Dim D = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)
    '-or-
    Dim D = DateTime.Now.ToString(New System.Globalization.CultureInfo("en-us"))