c# - asp.net C# 中的 SQL IN 运算符

标签 c# sql asp.net

我在绑定(bind) gridview 时遇到错误。我想使用 SQL IN 运算符从数据库中选择多条记录。请帮我解决这个问题。

aspx.cs代码

    string codeId = "4,3,5,7";
    int[] result = codeId.Split(',').Select(int.Parse).ToArray();


    string Qry = "select CodeId,Code,AccountHead,Rate from AccountHeads Where CodeId IN " + result;         //Getting error here     
    SqlDataAdapter adp = new SqlDataAdapter(Qry, con);
    DataTable dt = new DataTable();

    adp.Fill(dt);

    if (dt.Rows.Count > 0)
    {

        GridView1.DataSource = dt;
        GridView1.EmptyDataText = "no records founds";
        GridView1.DataBind();
        //Hide Gridview columns
        GridView1.Columns[0].Visible = false;

    }

最佳答案

您不需要使用 , 拆分字符串并使用 IEnumerable.Select 来选择 int 值。

已经IN clause 设置了一个格式良好的字符串.您只需要在 () 中使用您的值;

string Qry = string.Format(@"select CodeId,Code,AccountHead,Rate
                             from AccountHeads Where CodeId IN ({0})",
                             codeId);

关于c# - asp.net C# 中的 SQL IN 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28529209/

相关文章:

c# - 读取ISO 8859 1编码,用webclient下载xml流

c# - 隐藏工具栏绑定(bind)错误

c# - 将变量模型类型传递给 MVC 中的 C# 函数以简化代码

c# - ASP.NET 实体管理器 : create more than one entity in a view

c# - 在 Web API 中更新身份用户声明

c# - 如何在禁用 TLS1/SSL3 的情况下连接到 Azure 数据库

c# - 从 HTML 中删除所有空的/不必要的节点

sql - 具有动态(未知)列数的 T-Sql 查询

sql - 如何发现我创建的物化 View 的底层查询?

sql - 检索 SQL 中的最近事件