逗号分隔的 SQL 字符串 需要分隔 [英] Comma Delimited SQL string Need to separated

查看:39
本文介绍了逗号分隔的 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

这篇关于逗号分隔的 SQL 字符串 需要分隔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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