【问题标题】:Insert into Database Table only if DISTINCT仅当 DISTINCT 时才插入数据库表
【发布时间】:2014-11-01 08:44:41
【问题描述】:

我有一个列表,其中包含需要添加到表中的值,并且我已经编写了所有必要的要求,但是我需要添加这些值仅当它们不存在时已经有表了。

我的插入语句:

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();
            }

为了完成这项工作,我应该做些什么改变,伙计们? :) 谢谢!

【问题讨论】:

    标签: c# sql select insert distinct


    【解决方案1】:

    也许只是将where 添加到insert? (以及衡量良好衡量和评估效率的独特指标):

     where not exists (select 1 from NewWords where WordList = @WordList)
    

    【讨论】:

      【解决方案2】:

      如果您在另一个表中存储了姓名列表,那么您可以使用此查询

      insert into tbl_name 
      select * from tbl_name 
      where col_name not in(
          select * from ano_tbl_name
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-15
        • 2017-04-21
        • 1970-01-01
        • 2013-06-14
        • 1970-01-01
        • 2019-01-05
        • 2019-11-22
        相关资源
        最近更新 更多