0

问题:我使用 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)

单独并将其结果添加到我的数据表中的新列?

4

1 回答 1

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
于 2013-06-25T17:36:38.520 回答