使用 C# 从 SQL 数据库表中选择
我有一个用户 ID 列表和一个与 SQL Server 的开放连接。如何循环遍历此列表并选择与 First_Name 和 Last_Name 列匹配的 UserID?我假设输出可以在数据表中?
非常感谢
I have a List of UserID's and a open connection to SQL Server. How can I loop through this List and Select matching UserID with First_Name and Last_Name columns? I assume the output can be in a datatable?
many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据您运行的 SQL 类型,它会略有不同,但是这个 这应该可以帮助您入门。
It varies slightly depending on which type of SQL you're running, but this and this should get you started.
最方便的方法是:
将该 CSV 字符串提供到 IN 子句中,例如:
否则,您可以将值插入到临时表中并连接到用户表:
The most expedient way of doing this would be to:
Supply that CSV string into an IN clause, like:
Otherwise, you could insert the values into a temp table and join to the users table:
在 SQL 数据库中编写一个名为 ParseIntegerArray 的函数。这应该将逗号分隔的字符串转换为 ID 表,然后您可以在查询中加入该表。这还有助于避免连接字符串构建 SQL 时可能带来的任何 SQL 注入风险。使用 LINQ to SQL 或 LINQ to Entities 时也可以使用此函数。
Write a function in your SQL database named ParseIntegerArray. This should convert a comma delimited string into a table of IDs, you can then join to this in your query. This also helps to avoid any SQL injection risk you could get from concatenating strings to build SQL. You can also use this function when working with LINQ to SQL or LINQ to Entities.
本文应该对您有帮助:http://msdn. microsoft.com/en-us/library/aa496058%28SQL.80%29.aspx
我过去曾使用它来创建一个接受单个逗号分隔的 varchar 参数的存储过程。
我的 C# 程序源是一个选中的列表框,我使用 foreach 循环和 StringBuilder 构建了逗号分隔的字符串来进行串联。可能有更好的方法,具体取决于您列表中的项目数量。
回到 SQL 部分,本文中讨论的 fn_Split 函数使您能够将逗号分隔的字符串转换回 SQL Server 可以理解的表变量...并且您可以在存储过程中查询该变量。
下面是一个示例:
请注意,如果您愿意,还可以使用内部联接来代替 IN()。
如果您的 SQL Server 上没有 fn_Split UDF,您可以在此处找到它: http:// odetocode.com/Articles/365.aspx
我希望这会有所帮助。
This article should help you: http://msdn.microsoft.com/en-us/library/aa496058%28SQL.80%29.aspx
I've used this in the past to create a stored procedure accepting a single comma delimited varchar parameter.
My source from the C# program was a checked list box, and I built the comma delimited string using a foreach loop and a StringBuilder to do the concatenation. There might be better methods, depending on the number of items you have in your list though.
To come back to the SQL part, the fn_Split function discussed in the article, enables you to transform the comma delimited string back to a table variable that SQL Server can understand... and which you can query in your stored procedure.
Here is an example:
Note that you could also use an inner join, instead of the IN() if you prefer.
If you don't have the fn_Split UDF on your SQL Server, you can find it here: http://odetocode.com/Articles/365.aspx
I hope this helps.