合并来自2个表的数据

时间:2012-10-08 04:04:42

标签: c# sql visual-studio-2010 sql-server-2008

免责声明:这是测试/假人/假数据库

大家好,我有一个问题,下面是2个表结构。当我使用

SELECT CONVERT(char(80), InvDate,3) AS InvDate,InvoiceNo,EmployerCode,TaxAmount + SubTotal AS Amount,'' AS Payment FROM dbo.Invoice;

http://i48.tinypic.com/icpzpy.png

我希望在列中添加患者名称,其中将标记为发票编号。所以我的意思是,当执行查询时,它应该向我显示带有发票编号的患者详细信息。但在两个表结构中都没有链接。我能想到的唯一联系" MedicalRecordID"。我尝试使用UNION函数并没有给我所需的输出。有什么帮助吗?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace MedicalDataExporter
{
public partial class frmSales : Form
{
    public frmSales()
    {
        InitializeComponent();
    }


    private void dtpFrom_ValueChanged(object sender, EventArgs e)
    {

    }

    private void btnExtract_Click(object sender, EventArgs e)
    {

        SqlConnection objConn = new SqlConnection("Data Source=test;Initial Catalog=test;Persist Security Info=True;User ID=test;Password=test");

       System.Data.SqlClient.SqlConnection(conStr);
        objConn.Open();

        SqlCommand objCmd = new SqlCommand("SELECT CONVERT(char(80), InvDate,3) AS InvDate,InvoiceNo,EmployerCode,TaxAmount + SubTotal AS Amount,'' AS Payment FROM Invoice WHERE (InvDate >= CONVERT(datetime, '"+dtpFrom.Text +"', 105 )) AND (InvDate <= CONVERT(datetime, '"+dtpTo.Text+"', 105))", objConn);

        SqlDataReader objReader;
        objReader = objCmd.ExecuteReader();

        System.IO.FileStream fs = new System.IO.FileStream("C:\\CMSExportedData\\Sales-" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", System.IO.FileMode.Create);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.Default);

        int count = 0;
        while (objReader.Read())
        {

            for (int i = 0; i < 5; i++)
            {
                if (!objReader.IsDBNull(i))
                {
                    string s;
                    s = objReader.GetDataTypeName(i);
                    //MessageBox.Show(s);
                    if (objReader.GetDataTypeName(i) == "char")
                    {
                        sw.Write(objReader.GetString(i));
                    }
                    else if (objReader.GetDataTypeName(i) == "money")

                    {
                        sw.Write(objReader.GetSqlMoney(i).ToString());
                    }
                    else if (objReader.GetDataTypeName(i) == "nvarchar")
                    {
                        sw.Write(objReader.GetString(i));
                    }
                }
                if (i < 4)
                {
                    sw.Write("\t");
                }

            }
            count = count + 1;
            sw.WriteLine();

        }
        sw.Flush();
        fs.Close();
        objReader.Close();
        objConn.Close();
        MessageBox.Show(count + " records exported successfully.");
        this.Close();
    }

    private void groupBox1_Enter(object sender, EventArgs e)
    {

    }

    private void dtpTo_ValueChanged(object sender, EventArgs e)
    {

    }

    private void frmSales_Load(object sender, EventArgs e)
    {

    }
}
}

这是表结构:

http://i45.tinypic.com/2cwu2j6.png

这是第二个表结构:

http://i45.tinypic.com/29yplvl.png

1 个答案:

答案 0 :(得分:1)

要在多个表中查询数据,您需要join the tables。我不是100%清楚你的两个表之间的关系,但如果MedicalRecordID是正确的关系,那么你的查询应该是这样的:

SELECT
    CONVERT(char(80), i.InvDate,3) AS InvDate,
    i.InvoiceNo,
    i.EmployerCode,
    i.TaxAmount + i.SubTotal AS Amount,
    '' AS Payment,
    pd.LastName,
    pd.GivenName
FROM
    dbo.Invoice i
        INNER JOIN dbo.PatientDetails pd ON (pd.MedicalRecordID = i.MedicalRecordID)
;

如果表之间存在一对一的关系,并且每个发票始终有PatientDetails条记录,则此方法有效。如果PatientDetails是可选的,则使用LEFT JOIN代替INNER JOIN

编辑(对评论的回应):

我认为你的WHERE子句中的DateTime转换没有按照你期望的方式工作。假设dtpFromdtpToDatePicker控件,您可能希望使用SelectedDate属性而不是Text。此外,我强烈建议您在查询中使用参数,而不是连接字符串。您的代码将更清晰,您将避免使用SQL injection。这是一个简单的例子:

using (SqlConnection connection = new SqlConnection( ... ))
{
    connection.Open();

    string sql = @"
                SELECT
                    CONVERT(char(80), i.InvDate,3) AS InvDate,
                    i.InvoiceNo,
                    i.EmployerCode,
                    i.TaxAmount + i.SubTotal AS Amount,
                    '' AS Payment,
                    pd.GivenName
                FROM
                    dbo.Invoice i
                        LEFT JOIN dbo.PatientDetails pd ON (pd.MedicalRecordID = i.MedicalRecordID)
                WHERE
                    InvDate >= @fromDate AND InvDate <= @toDate";

    SqlCommand cmd = new SqlCommand(sql, connection);
    cmd.Parameters.AddWithValue("@fromDate", dtpFrom.SelectedDate);
    cmd.Parameters.AddWithValue("@toDate", dtpTo.SelectedDate);

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        // do stuff with results
    }
}