ADO.NET insert multiple values to SQL parameter

跟風遠走 提交于 2020-01-07 02:41:10

问题


I am receiving a Dictionary<string, string> and would like to forward its values to the DB inside SqlParameter. Is that even possible? This is the way I did it, and I am getting an error that column name doesn't match table definition.

SqlParameter param = new SqlParameter();
param.ParameterName = "@Values";

var sb = new StringBuilder();
foreach (var item in data)
{
    sb.Append("'" + item.Value + "', ");
}
param.Value = sb.ToString().TrimEnd(',');

string insertString = $"insert into {tableName} values (@Values)";
SqlCommand command = new SqlCommand(insertString, connection);

command.Parameters.Add(param);
command.ExecuteNonQuery();

回答1:


Sql server can't interpret the single variable you are passing as multiple values.
You can either generate your query with multiple variables, or use a table valued parameter.
For the first option, you must change the way you build your query:

var command = new SqlCommand();

var insertString = $"insert into {tableName} values (";
var sb = new StringBuilder(insertString);
int i = 0;
foreach (var item in data)
{
    sb.Append("@P").Append(i).Append(",");
    command.Parameters.Add("@P" + i, SqlDbType.VarChar).Value = item.Value;
    i++;
}
command.Connection = connection;
command.CommandText = sb.ToString().TrimEnd(",") + ");";
command.ExecuteNonQuery();

Note: Code was not tested, there might be some errors.

For the second option, You must use a stored procedure. I've never tried to pass table valued parameters to an inline query and I don't think it's possible.
This post (also linked in Alex K's comment) explains how to do that.




回答2:


Each value in the "Values" part of you t-SQL must be enclosed with parenthesis.

So, just change this line:

    sb.Append("'" + item.Value + "', ");

to:

    sb.Append("('" + item.Value + "'),");  // note: no space after the ,

Your tSQL would look something like this:

    insert into myTable values ('A', 'B', 'C',)

It needs to look like this (assuming you've only got 1 column in the table):

    insert into myTable values ('A'), ('B'), ('C')

And if your table contains multiple columns:

    insert into myTable (myColumn) values ('A'), ('B'), ('C')



回答3:


I think the best is create a split function in mssql (million of example in internet)and a stored. Pass a string comma(for example) separated to the stored Who call the function. Sorry for no example but i'm with my smartphone



来源:https://stackoverflow.com/questions/41676619/ado-net-insert-multiple-values-to-sql-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!