逗号分隔的 SQL 字符串 需要分隔
问题描述:
我有从 .net 应用程序获取的这个字符串A、B、C、D、E、F、
I have this string that i am getting from .net application A,B,C,D,E,F,
我想写一个像
set @string = 'A,B,C,D,E,F'
select * from tbl_test
where tbl_test.code in (@string)
这在 t-SQL 中不起作用,因为它使用 @string
作为一个字符串,它没有分隔值.有什么办法可以做到这一点吗?
This wont work in t-SQL because it is using the @string
as one string it is not separating the values. Is there any ways i can do this?
答
它认为最简单的方法是,动态 SQL 生成:
It think the easiest way to do it, will be, dynamic SQL generation:
// assuming select is a SqlCommand
string[] values = "A,B,C,D,E,F".Split(',');
StringBuilder query = new StringBuilder();
query.Append("select * from tbl_test where tbl_test.code in (");
int i = 0;
foreach (string value in values) {
string paramName = "@p" + i++;
query.Append(paramName);
select.Parameters.AddWithValue(paramName, value);
}
query.Append(")");
select.CommandText = query.ToString();
// and then execute the select Command