正在SQL Server表中查找唯一的行

本文关键字:唯一 查找 SQL Server 正在 | 更新日期: 2023-09-27 18:00:03

我在这里看一个例子:

http://msdn.microsoft.com/en-US/library/y06xa2h1(v=vs.80).aspx

string s = "primaryKeyValue";
DataRow foundRow = dataSet1.Tables["AnyTable"].Rows.Find(s);
if (foundRow != null) 
{
    MessageBox.Show(foundRow[1].ToString());
}
else
{
    MessageBox.Show("A row with the primary key of " + s + " could not be found");
}

他们没有指定dataSet1来自哪里,这是否代表某个数据库?

我试图在代码中使用这个例子来查找唯一的行,但我似乎无法实现这个语法。我只使用连接字符串打开与SQL的连接,并使用SqlDataAdapter执行函数。。。

编辑:

SqlConnection myConnection = new SqlConnection("Data Source=server; Initial Catalog=Dashboard; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
SqlDataAdapter da = new SqlDataAdapter();
try
        {
            //Opens the connection to the specified database
            myConnection.Open();
            //Specifies where the Table in the database where the data will be entered and the columns used
            da.InsertCommand = new SqlCommand("INSERT INTO DashboardLibAnswer(Id,Date,Time,Question,Details,Answer,Notes,EnteredBy,WhereReceived,QuestionType,AnswerMethod,TransactionDuration)"
                + "VALUES(@Id,@Date,@Time,@Question,@Details,@Answer,@Notes,@EnteredBy,@WhereReceived,@QuestionType,@AnswerMethod,@TransactionDuration)", myConnection);
            //Specifies the columns and their variable type where the data will be entered
            //Special note:  Conversion from String > DateTime will cause exceptions that will only import some part of data and not everything
            da.InsertCommand.Parameters.Add("@Id", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@Date", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Time", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Question", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Details", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Answer", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@Notes", SqlDbType.Text);
            da.InsertCommand.Parameters.Add("@EnteredBy", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@WhereReceived", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@QuestionType", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@AnswerMethod", SqlDbType.NVarChar);
            da.InsertCommand.Parameters.Add("@TransactionDuration", SqlDbType.NVarChar);
            //Using the global variable counter this loop will go through each valid entry and insert it into the specifed database/table
            for (int i = 0; i < counter; i++)
            {
                //Iterates through the collection array starting at first index and going through until the end
                //and inserting each element into our SQL Table
                DataSet dashboardDS = new DataSet();
                da.Fill(dashboardDS, "DashboardLibAnswer");
                DataTable dt = dashboardDS.Tables["DashboardLibAnswer"];
                foreach (DataColumn col in dt.Columns)
                {
                    if (col.Unique)
                    {
                        da.InsertCommand.Parameters["@Id"].Value = collection.getIdItems(i);
                        da.InsertCommand.Parameters["@Date"].Value = collection.getDateItems(i);
                        da.InsertCommand.Parameters["@Time"].Value = collection.getTimeItems(i);
                        da.InsertCommand.Parameters["@Question"].Value = collection.getQuestionItems(i);
                        da.InsertCommand.Parameters["@Details"].Value = collection.getDetailsItems(i);
                        da.InsertCommand.Parameters["@Answer"].Value = collection.getAnswerItems(i);
                        da.InsertCommand.Parameters["@Notes"].Value = collection.getNotesItems(i);
                        da.InsertCommand.Parameters["@EnteredBy"].Value = collection.getEnteredByItems(i);
                        da.InsertCommand.Parameters["@WhereReceived"].Value = collection.getWhereItems(i);
                        da.InsertCommand.Parameters["@QuestionType"].Value = collection.getQuestionTypeItems(i);
                        da.InsertCommand.Parameters["@AnswerMethod"].Value = collection.getAnswerMethodItems(i);
                        da.InsertCommand.Parameters["@TransactionDuration"].Value = collection.getTransactionItems(i);
                        da.InsertCommand.ExecuteNonQuery();
                    }
                }
                //Updates the progress bar using the i in addition to 1 
                _worker.ReportProgress(i + 1);
            } // end for
            //Once the importing is done it will show the appropriate message
            MessageBox.Show("Finished Importing");
        } // end try
        catch (Exception exceptionError)
        {
            //To show exceptions thrown just uncomment bellow line
            //rtbOutput.AppendText(exceptionError.ToString);
        } // end catch
        //Closes the SQL connection after importing is done
        myConnection.Close();
    }

正在SQL Server表中查找唯一的行

如果您从数据适配器填充数据集,您将能够遵循相同的逻辑-http://msdn.microsoft.com/en-us/library/bh8kx08z(v=vs.71).aspx

这可能值得展示你实际上需要什么来获得更具体的帮助

编辑我想我已经理解你想要什么了——如果你从已经填充的表中填充数据表,只需在添加之前检查项目是否已经存在——即

if (dt.Rows.Find(collection.getIdItems(i)) == null)    
{
    // add your new row
}

(只是为了确定我做了一个快速测试——希望这能有所帮助):

  // MyContacts db has a table Person with primary key (ID) - 3 rows - IDs 4,5,6
  SqlConnection myConnection = new SqlConnection("Data Source=.; Initial Catalog=MyContacts; Integrated Security=SSPI; Persist Security Info=false; Trusted_Connection=Yes");
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand("select * from Person", myConnection);
        myConnection.Open();
        DataSet dashboardDS = new DataSet();
        da.Fill(dashboardDS, "Person");
        dashboardDS.Tables[0].PrimaryKey = new[] { dashboardDS.Tables[0].Columns["ID"]}; 
        List<int> ids = new List<int> {4, 6, 7};
        foreach (var id in ids)
        {
            if (dashboardDS.Tables[0].Rows.Find(id) == null)
            {
                Console.WriteLine("id not in database {0}", id); //i.e. 7
            }
        }

您首先需要打开与数据库的连接。这是一个很好的连接字符串来源:连接字符串参考。

然后,您需要用某个表中的数据填充数据集。由于我们只对模式信息感兴趣,所以我们只选择了一行(SELECT TOP 1 ...)。

然后我们可以遍历这些列并检查它们的Unique属性(布尔值):

string connString =
            "server=(local)''SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI";
string sql = @"SELECT TOP 1 * FROM AnyTable";
using (SqlConnection conn = new SqlConnection(connString)) {
    conn.Open();
    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
    using (DataSet ds = new DataSet()) {
        da.Fill(ds, "AnyTable");
        DataTable dt = ds.Tables["AnyTable"];
        foreach (DataColumn col in dt.Columns) {
            if (col.Unique) {
                Console.WriteLine("Column {0} is unique.", col.ColumnName);
            }
        }
    }
}

更新#1

对不起,我误解了你的问题。上面的示例返回唯一的列,而不是唯一的行。您可以通过在SQL:中使用DISTINCT关键字来获得唯一的(不同的)行

SELECT DISTINCT field1, field2, field3 FROM AnyTable

然后,您可以按照与上面相同的方式填写数据表。

在数据库术语中,"唯一"一词通常用于表示唯一约束和唯一索引。术语"不同"用于不同的行。


更新#2

您更新的问题似乎表明您不想查找唯一的行,而是想插入唯一的行(恰恰相反)。

通常,您会从这样的集合中选择不同的项目。然而,很难准确回答您的问题,因为我们不知道您收藏的类型。

foreach (var item in collection.Distinct()) {
}

更新#3

在SQL Server表中插入不同值的最简单方法是在从CSV文件中读取行时,在其原始位置过滤行;甚至在分开它们之前。

string[] lines = File.ReadAllLines(@"C:'Data'MyData.csv");
string[][] splittedLines = lines
                .Distinct()
                .Select(s => s.Split(','))
                .ToArray();

现在,您可以将不同(唯一)的拆分行插入SQL Server表中。