如何将字符串列表传递给SQL C#中的in子句? [英] How to pass string list to in clause in SQL C#?

查看:302
本文介绍了如何将字符串列表传递给SQL C#中的in子句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的字符串:

string ids = 170801 / 1,170801 / 2,170801/3<<这将是动态的不固定



现在我想解析这样的查询:

i have string like this:
string ids=170801/1,170801/2,170801/3 << This will be dynamic not fixed

Now i want to parse query something like this:

select min(value) from tab where id in(ids)





但它没有结果



i我试图将字符串传递给cluase但没有结果



我尝试过:



i尝试拆分字符串并创建数组但是没有输出



but it results nothing

i am trying to pass string to in cluase but no result

What I have tried:

i have tried splitting the string and creating array but is has no output

推荐答案

有两种方法可以做到这一点,一种快速而且脏(并且可能不安全,如果你的数据是动态的)并且一个复杂而干净。



快速而肮脏的是使用字符串连接:

There are two ways to do this, one quick and dirty (and probably unsafe, if your data is dynamic) and one complicated and clean.

The quick and dirty is to use string concatenation:
string rawCSV = "170801/1,170801/2,170801/3";
string ids = string.Join(",", rawCSV.Split(',').Select(s => "'" + s + "'"));

然后您可以将该字符串用作WHERE子句的一部分:

You can then use that string as part of the WHERE clause:

string sql = "SELECT MIN(value) FROM tab WHERE Id IN (" + ids" + ")";



但是......如果您的数据是动态的,这很危险 - 它让您对SQL注入完全开放,这可能会损坏或破坏您的数据库。< br / >


更好的解决方案要复杂得多。

您需要创建一个接受字符串参数的存储过程。

然后拆分它,并从中创建基于表格的数据。

见这里:在SQL IN子句中使用逗号分隔值参数字符串 [ ^ ]


这篇关于如何将字符串列表传递给SQL C#中的in子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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