繁体   English   中英

将针对数据表的查询结果添加到Visual Basic中另一个数据表中的列

[英]adding results of query against datatable to a column in another datatable in visual basic

问题:我已经使用SQL服务器数据库上的查询填充了数据表。 查询是:

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)

自行将其结果添加到我的数据表的新列中?

您始终可以将其嵌套在另一个查询中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM