【问题标题】:adding results of query against datatable to a column in another datatable in visual basic将针对数据表的查询结果添加到Visual Basic中另一个数据表中的列
【发布时间】:2013-06-25 17:27:48
【问题描述】:

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

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

【问题讨论】:

  • 该代码易受 sql 注入攻击。你实际上是在乞求被黑。

标签: sql vb.net datatable


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-22
    • 2016-01-02
    • 2015-06-11
    • 1970-01-01
    • 2016-12-16
    • 1970-01-01
    • 2011-10-26
    • 2016-09-22
    相关资源
    最近更新 更多