我对编码和SQL很新。我有以下(部分)代码,它可以工作,但日期应作为参数传递。我该怎么做?
sqlStr = "DECLARE @MYDATE DATETIME, @MYDATE2 DATETIME"
sqlStr &= " SET @MYDATE = '" & fromDate.ToString("MM-dd-yyyy") & "'" & ""
sqlStr &= " SET @MYDATE2 = '" & toDate.ToString("MM-dd-yyyy") & "'" & ""
Dim da As New SqlDataAdapter(sqlStr, conn)
ds = New DataSet
da.Fill(ds, "DevLog")
da.Dispose()
Return ds
我需要执行.ToString
操作,因为来自系统的日期是xx.xx.xxxx (fi-FI)
而不是xx-xx-xxxx (en-US)
,因为SQL想要它们(该死的美国人......))。
所以,我希望将这些日期作为SQL参数传递,如@fromDate = fromDate
,但由于我不熟悉编码和SQL,我需要帮助。我在哪里以及如何插入??
command.parameters.Add(@fromDate, DATETIME)
command.parameters.Add(@toDate, DATETIME)
编辑:对不起,我搞错了。其实我要说的是:
command.parameters.Add("@toDate", SqlDbType.DateTime).Value = toDate
我应该以某种方式传递fromDate和toDate作为正确的DATETIME参数形式在SQL字符串(@fromdate和@toDate)而不是我现在正在做的方式...作为ToString转换。
@Saagar Elias Jacky
sqlStr = "DECLARE @MYDATE DATETIME, @MYDATE2 DATETIME"
sqlStr &= " SET @MYDATE = '" & fromDate.ToString("MM-dd-yyyy") & "'" & ""
sqlStr &= " SET @MYDATE2 = '" & toDate.ToString("MM-dd-yyyy") & "'" & ""
sqlStr &= " SELECT FixedDate, persons.FirstName, persons.lastName, TimeStampRecord, HoursSpent, HoursSpentRow, HoursSpentType"
sqlStr &= " FROM DevLog"
sqlStr &= " INNER JOIN Persons ON DevLog.OwnerUserID=Persons.UserID"
sqlStr &= " WHERE TimeStampRecord=1"
sqlStr &= " AND FixedDate BETWEEN @MYDATE AND @MYDATE2"
答案 0 :(得分:1)
sqlStr = "SELECT * FROM DevLog "
sqlStr &= " INNER JOIN Persons ON DevLog.OwnerUserID=Persons.UserID"
sqlStr &= " WHERE TimeStampRecord = 1"
sqlStr &= " AND FixedDate BETWEEN @MYDATE AND @MYDATE2"
Dim ds As DataSet
Using sqlComm As New SqlCommand(sqlStmt, sqlConn)
sqlComm.Parameters.AddWithValue("@fromDate", fromDate)
sqlComm.Parameters.AddWithValue("@toDate", toDate)
Dim da As New SqlDataAdapter(sqlStmt, sqlConn)
ds = New DataSet()
da.Fill(ds, "DevLog")
da.Dispose()
End Using
未经测试,但希望有所帮助