我有一个列表,其中包含需要添加到表中的值,并且我已为其编写了所有必需的要求但是我需要添加值仅在它们不存在的情况下表已经。
我的插入声明:
public static void InjectNewWords(List<string> newWords)
{
string conString = "Data Source=.;Initial Catalog=QABase;Integrated Security=True";
List<string> distinctWords = newWords.Distinct().ToList();
using (SqlConnection connection = new SqlConnection(conString))
{
connection.Open();
string sqlIns = "insert into NewWords(WordList) values (@WordList)";
SqlCommand command = new SqlCommand(sqlIns, connection);
command.Parameters.Add("@WordList", SqlDbType.Text);
try
{
foreach (string word in distinctWords)
{
command.Parameters["@WordList"].Value = word;
command.ExecuteNonQuery();
}
}
catch(Exception ee)
{
Console.WriteLine(ee.ToString());
}
try
{
Int32 rowsAffected = command.ExecuteNonQuery();
//Console.WriteLine("RowsAffected: {0}", rowsAffected);
//("Rows Affected: " + rowsAffected);
connection.Close();
newWords.Clear();
distinctWords.Clear();
}
为了完成这项工作,我应该做些什么改变?伙计们? :)谢谢!
答案 0 :(得分:1)
或许只需向where
添加insert
? (以及衡量评估和评估效率的独特指标):
where not exists (select 1 from NewWords where WordList = @WordList)
答案 1 :(得分:0)
如果您在另一个表中存储了名称列表,那么您可以使用此查询
insert into tbl_name
select * from tbl_name
where col_name not in(
select * from ano_tbl_name
);