【问题标题】:Put multiple row values in object in VB.NET在 VB.NET 的对象中放置多个行值
【发布时间】:2015-08-26 16:18:58
【问题描述】:

我有一个存储过程,该过程通常会返回多行,例如:

ID     Type    Price
1234    A      2.260
1234    B      2.690
1234    C      2.990
1234    D      2.690
1234    D      2.790
1234    D      2.650
1234    D      2.680

我想输出每种类型的最新值。在我的数据阅读器中,我有:

While dr.Read
    result.price.TypeA= dr("price")
    result.price.TypeB= dr("price")
    result.price.TypeC= dr("price")
    result.price.TypeD= dr("price")
End While

我的查询看起来像:

select  sm_id,
        type,
        price
from    ** WITH (NOLOCK)
where   id = @id
order by id desc

我不确定如何将所有结果存储到我的对象中,以便我可以在前端访问它们。

【问题讨论】:

  • LINQ。 LINQ 是您的答案。请参阅此处 stackoverflow.com/questions/157786/…stackoverflow.com/questions/14502428/… 。我试图打出一个答案,但有太多的假设和未知数无法连贯。您的查询的问题之一是所有 ID 似乎都相同。如果这不是错字,您将需要一个唯一标识符;我建议ROW_NUMBER()
  • 另外,您的查询将是选择按类型分组的最大 ID
  • “输出最新值”——如何确定最新值?
  • @T.S.发布此内容后,我意识到我需要查询另一列。我现在将更新日期作为查询的一部分。
  • @rlb.usa 非常感谢!我去看看!

标签: sql .net vb.net


【解决方案1】:

这可能不是最高效的查询,但它会按照您的描述完成工作

select t1.id, t1.t, t1.maxDt, t2.price
from 
    (select id, [TYPE] t, MAX(ud) maxDt 
     from dbo.a it
     where id =1 
     group by id, [type]) t1 
         left join
     dbo.a t2 on t1.id = t2.id and t1.t = t2.[type] and t1.maxDt = t2.ud

现在,将结果存储在对象中并显示它

Public Class MyClass
    Public Property Id As Integer
    Public Property [Type] As String
    Public Property [Date] As DateTime
    Public Property Price As Decimal
End Class

. . . . . 

Dim myList As New List(Of MyClass)()
While dr.Read()
    Dim item As New MyClass()
    item.Id = dr("id")
    item.[Type] = dr("t")
    item.[Date] = dr("maxDt")
    item.Price = dr("price")
    myList.Add(item)
End While

myDataGrid.DataSource = myList

这大概就是你所需要的

【讨论】:

  • 这是显而易见的答案,是的,但听起来改变他的查询并不是他想做的事。听起来他想要他的蛋糕也吃,这可以完成,但更难。
  • @rlb.usa 免得看他说什么
  • @T.S.我完全可以更改查询。无论如何我可以传回整个对象吗?这就是分组的作用吗?
  • @ryandonohue 请查看我的更新答案。这对你来说应该是一个好的开始。分组完成选择最大日期/每种类型
猜你喜欢
  • 2022-01-15
  • 1970-01-01
  • 2015-06-18
  • 1970-01-01
  • 2018-09-17
  • 2021-02-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多