多个具有相同名称的SqlCommand参数

时间:2015-11-03 23:39:29

标签: c# asp.net sql-server vb.net parameters

我有一个查询,其中有多个具有相同名称的命名参数,我必须传递值。请考虑以下示例(在非存储过程后面的代码中查询):

firefoxbrowser

我使用以下代码段将值传递给fld3:

program

运行时,它为@ fld3提供标量变量错误(并且在调试fld3_val中有一个值)。因此,作为一种解决方法,我按如下方式使用它来声明三个命名参数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)"

cmd = New SqlCommand(stSqlQry)
cmd.Parameters.AddWithValue("@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

将值传递给多个SQL参数

1 个答案:

答案 0 :(得分:0)

对我有用并可能对你有用的一件事就是挑出字段名称。

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)"