【问题标题】:Add Parameter in a query in MS SQL在 MS SQL 的查询中添加参数
【发布时间】:2015-08-21 12:42:39
【问题描述】:

我正在使用 Visual Basic 和 MS SQL,我想知道如何在我的查询中添加参数。一般来说,我从我的数据库中读取一个表,然后在另一个 VB 类中复制一些字段:

Dim data = From e In table
           Where e.param >= param
           Select New VBClass With {
               .field1 = e.field1
               .field2 = e.field2
           }

问题是我想在查询中添加一个参数,例如如果字符串不为空,则查询变为:

Dim data = From e In table
           Where e.param >= param And e.StrParam = StrInput
           Select New VBClass With {
               .field1 = e.field1
               .field2 = e.field2
           }

否则查询保持不变。

【问题讨论】:

  • 如果您使用 MS SQL Server,为什么要使用 MySQL? (不要标记未涉及的产品。)
  • 对不起,如果我不明白,但我可以告诉你类似的代码正在使用 MS SQL Server。

标签: asp.net sql-server vb.net


【解决方案1】:

你可以用一个简单的If 语句来做到这一点:

Dim data as IEnumerable(Of VBClass)

If string.IsNullOrEmpty(StrInput) Then
    data = From e In table
           Where e.param >= param And e.StrParam = StrInput
           Select New VBClass With {
               .field1 = e.field1
               .field2 = e.field2
           }
Else
    data = From e In table
           Where e.param >= param And e.StrParam = StrInput
           Select New VBClass With {
               .field1 = e.field1
               .field2 = e.field2
           }
End If

如果你有很多独立的价值观,那么你可以这样做:

Dim query = table.Where(Function (e) e.param >= param)

If Not string.IsNullOrEmpty(StrInput) Then
    query = query.Where(Function (e) e.StrParam = StrInput)
End If

' Repeat for each property

Dim data = From e In query
           Select New VBClass With {
               .field1 = e.field1
               .field2 = e.field2
           }

在您枚举之前不会执行查询,因此这是非常有效的(嗯,因为它可以单独检查这么多列)

【讨论】:

  • 问题是我的班级有 80 个属性,所以我正在寻找不同的解决方案
猜你喜欢
  • 2022-11-04
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 2019-12-30
  • 2022-12-04
  • 2016-01-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多