简体   繁体   中英

Merging data from 2 tables

DISCLAIMER : THIS IS A TEST/DUMMY/FAKE DATABASE

Hi guys, i have a problem, below are the 2 table structures. When i use

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

在此处输入图片说明

I wish to add in a column patients name where by it will be tagged to invoice number. So what i mean is that, when the query is executed, it should show me the patientdetails tagged together with invoice number. But in the both table structures there are no links. The only linkage i can think of "MedicalRecordID". I'm tried using UNION function didnt give me the desired output. Any help?

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)
    {

    }
}
}

Here is the table structure:

在此处输入图片说明

Here is the 2nd table structure:

在此处输入图片说明

To query data across multiple tables, you want to join the tables . I'm not 100% clear on the relationship between your two tables, but if MedicalRecordID is the correct relationship, then your query should look something like this:

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

This works if there is a one-to-one relationship between tables, and if there is always a PatientDetails record for each invoice. If PatientDetails is optional, then use LEFT JOIN instead of INNER JOIN .

EDIT (response to comment):

I'm betting that the DateTime conversion in your WHERE clause is not working the way you expect. Assuming that dtpFrom and dtpTo are DatePicker controls, you probably want to use the SelectedDate property instead of Text . Also, I would highly recommend using parameters in your queries rather than concatenating strings. Your code will be cleaner, and you'll avoid SQL injection . Here's a quick example:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM