字符串列表中的参数化in子句 [英] Parameterized in clause on list on strings

查看:111
本文介绍了字符串列表中的参数化in子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在字符串列表的子句中进行参数化

我尝试过的事情:

List< string> x = new List< string>(){一个",两个",三个"}
从员工中选择*,其中EMP_NAME IN(@names)
我如何使字符串对象列表成为参数化值
我从Employee的EMP_NAME IN(String.Join(,",x))那里尝试了select *,但是它没有像它理想地应为("one,two.three")那样工作(一个,"两个,"三个)任何想法我如何实现的.

How i cam do parameterized in clause on list of strings

What I have tried:

List<string> x= new List<string>(){"one","two","three"}
select * from Employee where EMP_NAME IN(@names)
How i can make the list of string object to parameterized value
I tried as select * from Employee where EMP_NAME IN(String.Join(",",x)) but it didn''t worked as it making as(''one,two.three'') ideally it should be("one","two","three") any idea how i can achieve this

推荐答案

如果您使用的是.NET,请尝试Dapper [ ^ ]:
If you''re using .NET, try Dapper[^]:
using (var connection = new SqlConnection("..."))
{
    var results = connection.Query<Employee>("SELECT * FROM Employee WHERE Emp_Name In @Names", new 
    { 
        Names = new List<string> { "One", "Two", "Three" }
    });
}


列表支持 [


List Support[^]

If you can''t use Dapper, you''ll have to add each item as a separate parameter:

using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand(string.Empty, connection))
{
    var sb = new StringBuilder();
    sb.Append("SELECT * FROM Employee WHERE Emp_Name In (");
    
    for (int index = 0; index < list.Count; index++)
    {
        if (index != 0) sb.Append(", ");
        
        string parameterName = "@Name" + index;
        command.Parameters.AddWithValue(parameterName, list[index]);
        sb.Append(parameterName);
    }
    
    sb.Append(')');
    command.CommandText = sb.ToString();
    
    ...
}


这篇关于字符串列表中的参数化in子句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆