问题
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