Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# in语句不使用值传递参数_C#_Sql - Fatal编程技术网

C# in语句不使用值传递参数

C# in语句不使用值传递参数,c#,sql,C#,Sql,我有一个store prog,其中获取在组复选框中选中的部门。当我传递一个值时,它工作,但当我传递超过2个时,它不工作 店内程序 CREATE PROCEDURE [dbo].[REPORT] @dept nvarchar(max)=null AS set @dept=left(@dept,len(@dept)-1) select * from department where deptid in(@dept) 在我的代码背后 string dept = ""; foreach (Li

我有一个store prog,其中获取在组复选框中选中的部门。当我传递一个值时,它工作,但当我传递超过2个时,它不工作

店内程序

CREATE PROCEDURE [dbo].[REPORT]
    @dept nvarchar(max)=null
AS
set @dept=left(@dept,len(@dept)-1)
select * from department where deptid in(@dept)
在我的代码背后

string dept = "";
foreach (ListItem item in CheckBoxList1.Items)
{
    if(item.Selected)
    {
        dept+="'"+item.Value.ToString()+"',";
    }
}
...
...
...
cmd.Parameters.AddWithValue("@dept", dept);
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
    sda.Fill(dt);
    gvdata.datasource=dt;
    gvdata.bind();
}

一种方法是将查询转换为“动态”sql(执行sql字符串);这应该起作用:

SET @dept=left(@dept,len(@dept)-1)
exec('select * from department where deptid in(' + @dept + ')');

但是,在执行动态SQL时要注意注入攻击。

是否在@dept paramate中存储以逗号分隔的值?要使其正常工作,需要将SQL转换为字符串并执行该字符串。否则,您不能这样做。是的,我用逗号分隔该值。不要将代码标记为Javascript片段,除非它实际上是Javascript。。。请在发帖时多花一点时间格式化您的代码