在另一个查询中使用一个查询中的参数

时间:2019-01-03 14:32:56

标签: sql-server vb.net

我有一个带有15个参数的dbo.individuals sql表。该表应从后面绑定到gridview,但是在绑定之前,应根据另一个表dbo.activities的计算参数更新6个参数,该表包含10个参数。每个人都没有记录的活动,也没有数量不定的活动。查询2中使用的参数是varchar(50)数据类型。

我尝试了两种方法: 1:要在一个查询中加入两个表,但是用这种方法,我未能成功建立设想的个人表。 2:我尝试加载带有查询1的个人数据集,使用读取器循环浏览这些数据,并使用查询2中的varchar(50)id加载由另一个读取器循环浏览并经过分析的活动的数据集该表已建立。最终表应混合使用查询1和查询2的参数。但是,我无法管理查询2的功能。

Private Sub BindData()

    ' define table
    Dim dta As New DataTable()
    dta.Columns.AddRange(New DataColumn() {
        New DataColumn("RecordID", GetType(Integer)),
        New DataColumn("tagID", GetType(String)),
        New DataColumn("animalID", GetType(String)),
        New DataColumn("calvingdate", GetType(String)),
        New DataColumn("24hoursallowancesup1", GetType(String)),
        New DataColumn("24hoursallowancesup2", GetType(String)),
        New DataColumn("accumulatedallowancesup1", GetType(Integer)),
        New DataColumn("accumulatedallowancesup2", GetType(Integer)),
        New DataColumn("visitswithin24hours1", GetType(Integer)),
        New DataColumn("visitswithin24hours2", GetType(Integer)),
        New DataColumn("totalvisits1", GetType(Integer)),
        New DataColumn("totalvisits2", GetType(Integer))
                        })
    Dim konr As String = " "

    Try
        Dim PrimaryConnection As String = ConfigurationManager.ConnectionStrings("PrimaryConnection").ToString()
        Dim sqlhk As String = "Select * FROM Individuals ORDER BY Individuals.tagID ASC"
        Dim cnhk As New SqlConnection(PrimaryConnection),
            cmdhk As New SqlCommand(sqlhk, cnhk)

        cnhk.Open()

        Dim readerhk As SqlDataReader = cmdhk.ExecuteReader

        While readerhk.Read()

            konr = readerhk("tagID")

            'define and reset for each loop
            Dim acc1 As Integer = 0
            Dim acc2 As Integer = 0
            Dim accperiod As String = 0
            Dim accumulatedsup1 As Integer = 0
            Dim accumulatedsup2 As Integer = 0
            Dim cowactive1 As String = "Y"
            Dim cowactive2 As String = "Y"
            Dim dayvisits1 As Integer = 0
            Dim dayvisits2 As Integer = 0
            Dim totalvisits1 As Integer = 0
            Dim totalvisits2 As Integer = 0
            Dim eatensup1day As Integer = 0
            Dim eatensup2day As Integer = 0
            Dim eatentotal1 As Integer = 0
            Dim eatentotal2 As Integer = 0

            Try
                Dim caConnection As String = ConfigurationManager.ConnectionStrings("PrimaryConnection").ToString()
                Dim sqlca As String = "Select Activities.[ID], Activities.[VisitTime], Activities.[GramSup1], Activities.[GramSup2], Activities.[Comment] FROM Activities WHERE Activities.[EarTag] = '" & konr & "' ORDER BY Activities.[EarTag] ASC"
                Dim cnca As New SqlConnection(caConnection),
                cmdca As New SqlCommand(sqlca, cnca)

                'cmdca.Parameters.AddWithValue("@konr", readerhk("tagID"))

                cnca.Open()

                Dim readerca As SqlDataReader = cmdca.ExecuteReader

                While readerca.Read()

                    Dim vti As DateTime = DateTime.Parse(readerca("VisitTime"))
                    Dim fsk As TimeSpan = Now() - vti
                    Dim def As Integer = fsk.TotalHours
                    'would logically not become negative, but for certainty, we ensure the figure is positive
                    If def < 0 Then
                        def = -def
                    Else
                        def = def
                    End If

                    'visits last 24h
                    If def <= 24 And (readerca("GramSup1") + readerca("GramSup2")) > 0 Then
                        dayvisits1 += 1
                        dayvisits2 += 1
                        eatensup1day += readerca("GramSup1")
                        eatensup2day += readerca("GramSup2")
                    End If
                    'visits in accumulationperiod
                    If def <= (24 * Session("accperiod")) And (readerca("GramSup1") + readerca("GramSup2")) > 0 Then
                        totalvisits1 += 1
                        totalvisits2 += 1
                        eatentotal1 += readerca("GramSup1")
                        eatentotal2 += readerca("GramSup2")
                    End If

                End While

                Dim vtik As DateTime = DateTime.Parse(readerhk("calvingdate"))
                Dim fskk As TimeSpan = Now() - vtik
                Dim defk As Integer = fskk.TotalHours
                If defk < 0 Then
                    defk = -defk
                Else
                    defk = defk
                End If

                If defk >= (Session("accperiod") * 24) Then
                    accperiod = (Session("accperiod") * 24)
                Else
                    accperiod = defk
                End If

                Dim start1 As DateTime = vtik.AddDays(Session("startday1"))
                Dim end1 As DateTime = vtik.AddDays(Session("endday1"))
                Dim start2 As DateTime = vtik.AddDays(Session("startday2"))
                Dim end2 As DateTime = vtik.AddDays(Session("endday2"))

                If DateTime.Parse(Now()) >= DateTime.Parse(start1) And DateTime.Parse(Now()) <= DateTime.Parse(end1) Then
                    accumulatedsup1 = accperiod / 24 * readerhk("24hoursallowancesup1") - eatentotal1
                Else
                    cowactive1 = "N"
                End If
                If DateTime.Parse(Now()) >= DateTime.Parse(start2) And DateTime.Parse(Now()) <= DateTime.Parse(end2) Then
                    accumulatedsup2 = accperiod / 24 * readerhk("24hoursallowancesup2") - eatentotal2
                Else
                    cowactive2 = "N"
                End If

                dta.Rows.Add(readerhk("Id"), readerhk("tagID"), readerhk("animalID"), readerhk("calvingdate"), readerhk("24hoursallowancesup1"), readerhk("24hoursallowancesup2"), If(cowactive1 = "N", Nothing, accumulatedsup1), If(cowactive2 = "N", Nothing, accumulatedsup2), If(cowactive1 = "N", Nothing, dayvisits1), If(cowactive2 = "N", Nothing, dayvisits2), eatentotal1, If(cowactive2 = "N", Nothing, totalvisits2))

                readerca.Close()
                readerca = Nothing
                cnca.Close()
                cnca = Nothing

            Catch ex As Exception
                Response.Write("Cow log data error: " & ex.Message)
            End Try
        End While
                    Catch ex As Exception
        Response.Write("Cow listing error:" & ex.Message)
    End Try

    '-- Declaring of a DataView to be used as DataSource for a second grid
    Dim dv As New DataView(dta) With {
        .Sort = "visitswithin24hours1 ASC, visitswithin24hours2 ASC"
    }

    ' BIND DATABASE WITH THE GRIDVIEW
    GridView1.DataSource = dv
    GridView1.DataBind()

End Sub

我想要一个表,将个人的ID列为第1列,这是来自个人表/查询1的四个参数,以及来自活动表/查询2的六个参数。 我对此很业余,问题是应该从活动表/查询2计算的六个参数全为零(默认值),并且查询2显然未激活。我希望有人能帮助我。

表1 /个人的示例数据和数据类型:

  • [Id] INT IDENTITY(1,1)NOT NULL -123,
  • [HerdCountryCows] INT NOT NULL-278,
  • [HerdNumberCows] INT不为空-29034,
  • [SN_Cows] VARCHAR(16)NOT NULL-N67eF45G,
  • [tagID] VARCHAR(50)NOT NULL-208_0029034098564,
  • [animalID] VARCHAR(50)NULL-玫瑰,
  • [calvingdate] DATETIME2(7)NOT NULL-03012019 12:34:23,
  • [24hoursallowancesup1]整数默认值((100))非空-100,
  • [24hoursallowancesup2]整数默认值((100))非空-100,
  • [accumulatedallowancesup1] INT默认((0))非空-456,
  • [accumulatedallowancesup2] INT默认((0))非空-0,
  • [visitswithin24hours1] INT DEFAULT((0))NOT NULL-4,
  • [visitswithin24hours2] INT DEFAULT((0))NOT NULL-0,
  • [totalvisits1]缺省值((0))非空-12,
  • [totalvisits2] INT默认((0))非空-0,

表2 /活动的示例数据和数据类型:

  • [ID]整数(1,1)非空-4356,
  • [EarTag] VARCHAR(50)NOT NULL-208_0029034098564,
  • [VisitTime] DATETIME2(7)NOT NULL-03012019 12:34:23,
  • [GramSup1] INT NOT NULL-23,
  • [GramSup2] INT NOT NULL-12,
  • [评论] VARCHAR(100)NULL-评论,
  • [SlaveID] VARCHAR(50)非空-MSF0098,
  • [国家/地区] VARCHAR(50)非空-278,
  • [Herd] VARCHAR(50)NOT NULL-29034,
  • [SN_Log] VARCHAR(16)NULL-N67eF45G,
  • [ActivityType] INT NULL-7,

1 个答案:

答案 0 :(得分:1)

我认为您要查找的是对两个表进行“交叉应用”:

类似的东西

Select *
FROM Individuals I CROSS APPLY
(
    Select min([VisitTime]) as first_visit, count(*) as Activities_cnt
    FROM Activities 
    WHERE Activities.[EarTag] = I.tagID
) as Activities_cum
ORDER BY Individuals.tagID ASC;

更多信息: When should I use Cross Apply over Inner Join?