首页 > 解决方案 > 编写用于过滤 SQL Server 表属性的 VB.Net 代码

问题描述

我的 SQL Server 表中有几列,并且想要过滤“承包商”列。在“承包商”列中,用户可以选择两个名称“Namal”和“其他”,如屏幕截图所示。

我想要的是仅获得“Namal”而不是“其他”的“金额”总和

这是我编写但无法正常工作的代码。这里@d1@d2是用户可以选择的日期范围。

Imports System.Data.SqlClient
Public Class Form6
    Dim connection As New SqlConnection("server=(local); Database=Luminex; integrated security=true")

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim table As New DataTable()
        Dim command As New SqlCommand("select sum(Amount) as a  from PeoTVDB where Date between @d1 and @d2 and Contractor= @Namal", connection)

        command.Parameters.Add("@d1", SqlDbType.Date).Value = DateTimePicker1.Value
        command.Parameters.Add("@d2", SqlDbType.Date).Value = DateTimePicker2.Value

        Dim adapter As New SqlDataAdapter(command)
        adapter.Fill(table)

        Label1.Text = table.Rows(0)("a").ToString()    

    End Sub        
End Class

标签: sql-servervb.net

解决方案


将数据库对象保留在使用它们的方法的本地。如果您在多个地方使用连接字符串,则将其放置为类级别变量。

数据库对象需要关闭和处置。Using...End Using即使出现错误,blocks 也会为您解决这个问题。

我认为 Date 可能是 Sql Server 中的保留字,所以我用括号对其进行了转义。即使不保留也不会伤害任何东西。

我很高兴看到Parameters.Add方法。唯一的问题是你忘记了一个。我不得不猜测类型和值是什么。

由于您只请求一条数据,您可以使用.ExecuteScalarwhich 返回一个对象,因此CDec()

Private ConString As String = "server=(local); Database=Luminex; integrated security=true"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim Amount As Decimal
    Using connection As New SqlConnection(ConString),
        command As New SqlCommand("select COALESCE(sum(Amount), 0) as a  from PeoTVDB where [Date] between @d1 and @d2 and Contractor= @Namal", connection)
        command.Parameters.Add("@d1", SqlDbType.Date).Value = DateTimePicker1.Value
        command.Parameters.Add("@d2", SqlDbType.Date).Value = DateTimePicker2.Value
        command.Parameters.Add("@Namal", SqlDbType.NVarChar, 200).Value = "Some Value"
        connection.Open()
        Amount = CDec(command.ExecuteScalar)
    End Using
    Label1.Text = Amount.ToString
End Sub

推荐阅读