![](/img/trans.png)
[英]Creating SqlDataSource SelectParameters for IN Clause Parameterized queries
[英]How to Parameterized Queries with the SqlDataSource (VB)
這是我在 VB.NET 中運行參數化查詢的代碼示例:
Dim sqlconn As New SqlConnection(connectionString)
sqlconn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Select * from TAble1 Where SkuCode in (@SKU)"
cmd.Connection = sqlconn
Dim parm As New SqlParameter
parm.Value ="1" 'This is working
parm.ParameterName = "@SKU"
cmd.Parameters.Add(parm)
Dim ds As New DataSet
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
MsgBox("Done")
Else
MsgBox("Not done.")
End If
如果我在 VB.NET 中運行此示例,則會成功返回結果。
但是在嘗試獲得多個記錄的結果時出現問題......這是行不通的。
請檢查並建議我們必須做的更改才能在帶參數的查詢中運行。
'parm.Value = "N'1', N'2'" 'this does not work.
'parm.Value = "'1','2'" 'this does not work.
我已經嘗試了這些參數值,但它不起作用。
SQL 參數是標量並且只接受單個值。 您可以使用 sqldbtype.Structured,盡管它有點復雜。
我發現如果您需要為IN
傳遞一組參數,其中參數的數量是動態的,最有效的方法(不幸的是)是:
我在下面提供了 linq 選項的示例。
Dim sqlParams As Dictionary(Of String, Integer) = integers.ToDictionary(Function(i) $"@ParamValue{i}", Function(i) i)
Dim ds As New DataSet
Dim dt As DataTable
Using db as new SqlConnection(conn)
conn.open()
Using cmd As New SqlCommand($"SELECT * FROM Table1 WHERE SkuCode IN (-1, {String.Join(", ", sqlParams.Select(Function(f) f.Key))}", db)
cmd.Parameters.AddRange(sqlParams.Select(Function(f) New SqlParameter(f.Key, SqlDbType.BigInt).Value = f.Value).ToArray())
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
dt = ds.Tables(0)
End Using
End Using
MsgBox(If(dt.Rows.Count > 0, "Done", "Not done"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.