我正在使用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
}
否则查询保持不变。
答案 0 :(得分:0)
您可以使用简单的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
}
在你枚举之前不会执行查询,所以这非常有效(好吧,因为它可以单独检查这么多列)