问题:我在sql server数据库上使用查询填充了数据表。查询是:
Select ID, startDate, codeID, Param,
(select top 1 startDate from myTable
where ID='" & ID & "' and Param = mt.param and codeID = 82 and startDate >= '" & startDate & "' and startDate >=mt.startDate
ORDER BY startDate)endTime,
from myTable mt where ID = '" & ID & "'
AND (startDate between '" & startDate & "' AND '" & endDate & "' AND (codeID = 81))
我想要一个名为duration的新列,它将是endTime和startDate之间的差异,以毫秒为单位。我不能只是在上面的查询中添加另一个子查询,因为在子查询运行之前,endTime列不存在。
那么,有没有办法可以运行第一个查询来填充数据表,然后运行如下查询:
Select DateDiff(ms,endTime,startDate)
单独将其结果添加到我的数据表中的新列?
答案 0 :(得分:1)
您始终可以将其嵌套在另一个查询中:
select *, datediff(ms, startDate, endTime)
from (
<your existing query here>
) t
当我在这里时,您似乎需要参数化查询课程:
Dim result As New DataTable
Dim Sql As String = _
"SELECT *, datediff(ms, startDate, endTime) FROM (" & _
"SELECT ID, startDate, codeID, Param, " & _
"(select top 1 startDate from myTable " & _
"where ID= @ID and Param = mt.param and codeID = 82 and startDate >= @startDate and startDate >=mt.startDate " & _
"ORDER BY startDate) endTime " & _
" FROM myTable mt " & _
" WHERE ID = @ID AND startDate between @startDate AND @endDate AND codeID = 81" & _
") t"
Using cn As New SqlConnection("connection string"), _
cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("@ID", SqlDbType.VarChar, 10).Value = ID
cmd.Parameters.Add("@startDate", SqlDbType.DateTime).Value = Convert.ToDateTime(startDate)
cmd.Parameters.Add("@endDate", SqlDbType.DateTime).Value = Convert.ToDateTime(endDate)
cn.Open()
Using rdr = cmd.ExecuteReader()
result.Load(rdr)
rdr.Close()
End Using
End Using