主详细记录的SQL查询

时间:2013-11-03 08:15:23

标签: c# asp.net sql-server gridview

我有两张桌子:

  • Document(列DocNo, Doctype, DocTitle
  • Registration(列:RegNo, DocNo, RedDate, Location

为了显示数据,我编写了这个存储过程:

CREATE Proc Show_Data_ByTitle
    @Title nvarchar(20)
AS
    SELECT * FROM Document WHERE DocTitle = @Title;

    SELECT * FROM Registration 
    WHERE DocNo IN (SELECT DocNo FROM Document WHERE DocTitle = @Title);

现在我想在gridview -asp.net页面显示结果 -

我该怎么做?

1 个答案:

答案 0 :(得分:0)

首先,我认为您需要在SQL语句中使用内部联接

SELECT * FROM
Document INNER JOIN Registration
ON Document.DocNo=Registration.DocNo
Where Document.DocTitle=@Title

接下来,如果您使用ADO.NET来解释数据,那么您可能希望类专用类来存储数据,如

public class DocumentRegistration
{
    public int DocNo {get; set;}
    public string DocType {get; set;}
    public string DocTitle {get; set;}
    public int RegNo {get; set;}
    public DateTime RedDate {get; set;}
    public string Location {get; set;}
}

接下来,您可以使用ADO.NET将数据导入您的班级

List<DocumentRegistration> list= new List<DocumentRegistration>();
SqlConnection conn = new SqlConnection();
conn.ConnectionString="YourConnectionString"
conn.Open();
SqlCommand cmd = new SqlCommand("Show_Data_ByTitle", conn);
SqlCommand cmd = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("Title", "yourtitle"));

SqlReader reader = cmd.ExecuteReader();
while(reader.Read())
{
    DocumentRegistration dr=new DocumentRegistration
    {
        DocNo =  Convert.ToInt32(reader["DocId"]);
        DocType =  Convert.ToString(reader["DocType"]);
        DocTitle = Convert.ToString(reader["DocTitle"]);
        RedDate = Convert.ToDateTime(reader["RedDate"]);
    }

    list.Add(dr);
}

//put this code where you want to load the list like PageLoad()
GridView1.DataSource=list;
GridView1.Databind();

希望这有帮助