2

在我用 C# 编写的应用程序中,我正在编写一个 SQL 查询。以下是查询

SELECT [Resource No_] where [Resource No_] In (@resources) 

@resources是具有一个或多个字符串的用户输入参数。

我的查询失败但没有显示错误

据我说,查询失败,因为@resources正在传递参数

"'123,'124','125'"

(开头和结尾有2 个逗号,这使我的查询失败)。

[Resource No_]是数据库中的类型NVARCHAR

谷歌搜索后,我在这个主题上找到了一些帮助,但所有的都适用于[Resource No_] 类型Integer

4

3 回答 3

5

虽然我不同意“重复问题”的选定答案(或许多棘手的答案),但这里有一个答案,它显示了一种与我的以下建议非常相似的方法。

(我已投票决定将这个问题作为重复问题结束,因为有这样的答案,即使被埋没了。)


只有一个SQL 值可以绑定到任何给定的占位符。

虽然有办法将所有数据作为“一个值”发送,但我建议动态创建占位符:它简单、干净,并且在大多数情况下都能可靠地工作。

考虑一下:

ICollection<string> resources = GetResources();

if (!resources.Any()) {
    // "[Resource No_] IN ()" doesn't make sense
    throw new Exception("Whoops, have to use different query!");
}

// If there is 1 resource, the result would be "@res0" ..
// If there were 3 resources, the result would be "@res0,@res1,@res2" .. etc
var resourceParams = string.Join(",",
    resources.Select((r, i) => "@res" + i));

// This is NOT vulnerable to classic SQL Injection because resourceParams
// does NOT contain user data; only the parameter names.
// However, a large number of items in resources could result in degenerate
// or "too many parameter" queries so limit guards should be used.
var sql = string.Format("SELECT [Resource No_] where [Resource No_] In ({0})",
    resourceParams);

var cmd = conn.CreateCommand();
cmd.CommandText = sql;

// Assign values to placeholders, using the same naming scheme.
// Parameters prevent SQL Injection (accidental or malicious).
int i = 0;
foreach (var r in resources) {
   cmd.Parameters.AddWithValue("@res" + i, r);
   i++;
}
于 2013-12-23T08:40:06.590 回答
1

使用用户定义的表类型来接受您的参数,然后在您的选择中使用 JOIN 子句来限制结果集。请参阅http://social.msdn.microsoft.com/Forums/en-US/2f466c93-43cd-436d-8a7c-e458feae71a0/how-to-use-user-defined-table-types

于 2013-12-23T08:33:40.830 回答
0

做类似的事情

resources.Aggregate(r1, r2 => r1 + "', '" + r2 + "'") 

并在一个字符串中传递列表。

于 2013-12-23T08:35:31.563 回答