如何为每一行选择评论

Raw*_*hi 0 c# sql t-sql sql-server-2005

我有events表,其中包括除了这么多的cols IdPK
和表格Comments,其中包括text,eventIdIdPK.
如何在一个单独的sql语句中选择事件信息及其注释,如何使用它以及它应该是什么样子的?

请注意,EventId(评论)= Id(事件)

Yve*_* M. 5

那应该这样做......

SELECT * FROM events
INNER JOIN comments on comments.eventid = events.id
Run Code Online (Sandbox Code Playgroud)

如果您不需要所有列,最好只选择您真正需要的列.

SELECT Id, eventId FROM events
INNER JOIN comments on comments.eventid = events.id
Run Code Online (Sandbox Code Playgroud)

要在C#代码中提取它,您可以使用以下System.Data样式:

using (SqlConnection connection = new SqlConnection("Put your ConnectionString here"))
{
    connection.Open();
    using (SqlDataAdapter adapter = new SqlDataAdapter("My SQL from Above", connection))
    {
        DataTable table = new DataTable();
         adapter.Fill(table);
         // now you can do here what ever you like with the table...

         foreach(DataRow row in table.Rows)
         {
            if (row.IsNull("Text") == false)
               Console.WriteLine(row["Text"].ToString());
         }
    }
}
Run Code Online (Sandbox Code Playgroud)