具有相同名称的多个SqlCommand参数
本文关键字:SqlCommand 参数 | 更新日期: 2023-09-27 18:20:23
我有一个带有多个同名命名参数的查询,我必须为其传递值。考虑以下示例(在非存储过程后面的代码中查询):
Dim stSqlQry As String = "Select fld1, fld2, fld3 From tbl1 Where fld3=@fld3
AND fld1 NOT IN(Select Distinct fld1 From tbl2 Where fld3=@fld3)
AND fld2 NOT IN(Select Distinct fld2 From tbl3 Where fld3=@fld3)"
我使用以下代码段将值传递给fld3:
cmd = New SqlCommand(stSqlQry)
cmd.Parameters.AddWithValue("@fld3", fld3_val)
运行时,它为@fld3提供标量变量错误(在调试中fld3_val有一个值)。因此,作为一种变通方法,我使用它如下,声明三个命名参数fld3_1, fld3_2, fld3_3
:
Dim stSqlQry As String = "Select fld1, fld2, fld3 From tbl1 Where fld3=@fld3_1
AND fld1 NOT IN(Select Distinct fld1 From tbl2 Where fld3=@fld3_2)
AND fld2 NOT IN(Select Distinct fld2 From tbl3 Where fld3=@fld3_3)"
并使用以下代码段将相同的值传递给fld3_1, fld3_2, fld3_3
:
cmd = New SqlCommand(stSqlQry)
cmd.Parameters.AddWithValue("@fld3_1", fld3_val)
cmd.Parameters.AddWithValue("@fld3_2", fld3_val)
cmd.Parameters.AddWithValue("@fld3_3", fld3_val)
第二个非常完美,第一个格式在后面的代码中不正确吗?有没有任何方法可以使用单个SqlCommand Parameter
将值传递给多个SQL参数?
对我有用并且可能对您有用的一件事是单独列出字段名。
Dim stSqlQry As String = "Select [fld1], [fld2], [fld3] From [tbl1] Where [fld3] = @fld3 AND [fld1] NOT IN(Select Distinct [fld1] From [tbl2] Where [fld3] = @fld3) AND [fld2] NOT IN(Select Distinct [fld2] From [tbl3] Where [fld3] = @fld3)"