【发布时间】:2017-06-21 12:19:34
【问题描述】:
我正在尝试使用以下 C# 代码运行存储过程
int intHowMany = docType.Count;
switch(intHowMany)
{
case 1:
string returntype1 = "'" + docType.ElementAt(0) + "'";
return returntype1;
case 2:
string returntype2 = "'" + docType.ElementAt(0) + "',"
+ "'" + docType.ElementAt(1) + "'";
return returntype2;
case 3:
string returntype3 = "'" + docType.ElementAt(0) + "',"
+ "'" + docType.ElementAt(1) + "',"
+ "'" + docType.ElementAt(2) + "'";
return returntype3;
case 4:
string returntype4 = "'"+docType.ElementAt(0)+"',"
+"'"+ docType.ElementAt(1)+"',"
+"'"+ docType.ElementAt(2)+"',"
+"'"+docType.ElementAt(3)+"'";
return returntype4;
case 5:
string returntype5 = "'" + docType.ElementAt(0) + "',"
+ "'" + docType.ElementAt(1)+"',"
+ "'" + docType.ElementAt(2)+"',"
+ "'" + docType.ElementAt(3)+"'"+","
+ "'" + docType.ElementAt(4)+"'";
return returntype5;
case 6:
string returntype6 = "'" + docType.ElementAt(0) + "',"
+ "'" + docType.ElementAt(1) + "',"
+ "'" + docType.ElementAt(2)
+ "'," + "'" + docType.ElementAt(3)
+ "'," + "'" + docType.ElementAt(4)
+ "'," + "'" + docType.ElementAt(5) +"'";
return returntype6;
case 7:
string returntype7 = "'"
+ docType.ElementAt(0) + "',"
+ "'" + docType.ElementAt(1) + "',"
+ "'" + docType.ElementAt(2) + "',"
+ "'" + docType.ElementAt(3) + "',"
+ "'" + docType.ElementAt(4) + "',"
+ "'" + docType.ElementAt(5) + "',"
+ "'" + docType.ElementAt(6) + "'";
return returntype7;
break;
}
return null;
}
以上代码为完成 SQL WHERE CloumnsName IN() 语句的 SQL 参数提供数据。
1、2 和 3 的 case 语句按预期工作。但是 case 语句 4 到 7 失败并显示以下错误消息:
字符串'LA)) order by inc_date_recvd desc;'后的非右引号。 'LA)) order by inc_date_recvd desc;' 附近的语法不正确。
以下是代码生成的文本字符串:
'CITIZEN CONCERN','CORRESPONDENCE LOG','INTEL','LAWSUIT'
'CITIZEN CONCERN','CORRESPONDENCE LOG','INTEL','LAWSUIT','EMAIL'
'CITIZEN CONCERN','CORRESPONDENCE LOG','INTEL','LAWSUIT','EMAIL','VIDEO'
'CITIZEN CONCERN','CORRESPONDENCE LOG','INTEL','LAWSUIT','EMAIL','VIDEO','WINDOW'
如您所见,字符串“LAWSUIT”中的第三个元素似乎带有右引号。我还把上面的字符串结果直接复制粘贴到了SQL server上的一个查询中,得到了预期的结果。
谁能看到这段代码有问题或解释为什么我不能让它工作。
【问题讨论】:
-
这就是为什么你应该不尝试编写动态SQL。您可以使用 LINQ-to-SQL 或 LINQ-to-EF 轻松生成
IN ()子句,使用where listOfIds.Contains(item.id) -
也许
return "'" + string.Join("',", docType) + "'"可以解决所有情况。 -
使用 Dapper
conn.Query<Item>("select * from sometable where id in (@ids)",ids)创建相同的语句更加容易,其中ids是一个 id 列表(数组、列表等) -
当您的内容包含
'时,这很容易出错,因此您的SQL 如下所示:'CITIZEN CONCERN', 'CORRESPONDENCE LOG', 'INTEL', 'LA'WSUIT'LAWSUIT中LA之后的'会导致此问题。除了整个函数是不好的做法之外,生成这样的 SQL 语句会带来SQL Injection的危险。这可能会以诉讼告终。 -
为什么要使用
case?为什么ElementAt()?为什么不检索所有元素并加入它们呢?如果docType是一个 IEnumerable,它的元素比你需要的多,你可以使用docType.Take(docType.Count)。或者你可以使用String.Format("\"{0}\""), String.Join(",",docType))
标签: c# sql-server