compare two tables and update the third one - c#

Suppose I have a table in SQL "abc" and with in it there is a column "number" and this column contains (1,2,3,4) etc.
In my second table "xyz" I have a column "number" and this column contains (1,2,3,4,5,6,7,8,9).
Now I want to compare these two and insert equal data within third table.
So how can I do this?
code :
string str = "SELECT Invoice_Details.PGI_ID, PARTY_BOOKING_DETAILS.PGI_ID AS abc ";
str += "FROM PARTY_BOOKING_MAIN INNER JOIN ";
str += " PARTY_BOOKING_DETAILS ON PARTY_BOOKING_MAIN.PBM_ID = PARTY_BOOKING_DETAILS.PBM_ID CROSS JOIN ";
str += " Invoice_Details where PARTY_BOOKING_MAIN.PM_ID = 1 ";
SqlConnection con = new SqlConnection("data source = .; database = ePartyDatabase01; integrated security = true");
con.Open();
SqlCommand cmd1 = new SqlCommand("update Invoice_Details set [status] = #a", con);
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr["PGI_ID"].ToString() == dr["abc"].ToString())
{
cmd1.Parameters.AddWithValue("#a", 1);
}
}
dr.Close();
cmd1.ExecuteNonQuery();
con.Close();

You probably want to use some kind of this query:
insert into table3 (number)
select
t1.number
from abc t1
inner join xyz t2
on t1.number = t2.number

I haven't tested this yet, but you might not even need C#, try something like this:
SELECT xyz.number
INTO third_table
FROM (
SELECT t1.number
FROM first_table t1 JOIN second_table t2 ON t1.number = t2.number
) AS xyz

Maybe something like this:
INSERT INTO table3(number)
SELECT
number
FROM
xyz
WHERE NOT EXISTS
(
SELECT
NULL
FROM
abc
WHERE
abc.number=xyz.number
)

Related

SQL Query Error in C#

I am new to SQL Queries, I want to load "PSX LAGA" Value from SettlementTypeSetup (Table) where Settlement Type is equals to Regular/BO and Sale / Purchase is equals to "Purchase";
below is my code and this is my table
private void Load_Settlement_Type()
{
SqlCeConnection conn = null;
SqlCeCommand cmd = null;
SqlCeDataReader rdr = null;
try
{
conn =
new SqlCeConnection(
#"Data Source=|DataDirectory|\Database.sdf;Persist Security Info=False");
conn.Open();
cmd = new SqlCeCommand("SELECT PSXLaga FROM SettlementTypeSetup where SettlementType=BO/REGULAR;" , conn);
rdr = cmd.ExecuteReader();
if (rdr == null)
{
MessageBox.Show("Reader is null");
}
else
{
while (rdr.Read())
{
PSXLAGATEXT = rdr["PSXLaga"].ToString();
}
rdr.Close();
cmd.Dispose();
}
}
finally
{
conn.Close();
PSXLagaTextBox.Text = PSXLAGATEXT;
}
}
****It gives me error: Column Name: BO/REGULAR not found, whereas BO/REGULAR is not a column name, BO/REGULAR is a value of a SettlementType (Column), The condition should be as follows.**
Give me PSX Laga Value where SettlementType(Column) value is
BO/REGULAR and Sale/Purchase(Column) is Purchase.
**
You need write your value in '' because it is a string. Other way is to do it using parameters.
cmd = new SqlCeCommand("SELECT PSXLaga FROM SettlementTypeSetup where SettlementType=#Type" , conn);
cmd.Parameters.AddWithValue("#Type", "BO/REGULAR");
This query means you want to retrieve PSXLaga from your SettlementTypeSetup table, where SettlementType equals to a given value. In your case this is BO/REGULAR. If your SettlementType is a string, you'll have to put quotes around your value like this: 'BO/REGULAR'
So your correct query would look like this:
"SELECT PSXLaga FROM SettlementTypeSetup WHERE SettlementType = 'BO/REGULAR';"
Edit: I see you also wanted to check if sale/purchase is equals to "Purchase". You can do this by adding this to your query: (I'm unsure if it likes the / in your table name though..)
"AND Sale/Purchase = 'Purchase'"
I suggest using mybirthname's answer though. It's objectively better than the query above.
Second edit: You forgot the quotes again. Incorrect:
"SELECT PSXLaga FROM SettlementTypeSetup where SettlementType="+settlementTypeComboBox.Text + " AND [Sale/Purchase]='Purchase'"
Correct:
"SELECT PSXLaga FROM SettlementTypeSetup WHERE SettlementType = '" + settlementTypeComboBox.Text + "' AND [Sale/Purchase] = 'Purchase';"
But again, try to write your code like mybirthname has shown. I don't have a lot of experience with queries in C# code.

Combo box Where Clause

i have a table of POMain po_no and a table of Shipping invoice, then when i search the po_no, i will add an invoice. the thing i want to do is if the po_no already have an invoice the po_no in search button will not appear
public AddForm()
{
InitializeComponent();
string ID = cb_po_search.SelectedValue.ToString();
string strPRSconn = ConfigurationManager.ConnectionStrings["POSdb"].ConnectionString;
SqlConnection sc = new SqlConnection(strPRSconn);
sc.Open();
string strQry = "SELECT POMain.po_no FROM POMain LEFT JOIN Shipping ON POMain.po_no = Shipping.po_no WHERE Shipping.invoice IS NULL AND POMain.po_no = '" + ID + "'";
SqlCommand scmd = new SqlCommand(strQry, sc);
SqlDataReader dr = scmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("po_no", typeof(string));
dt.Load(dr);
cb_po_search.ValueMember = "po_no";
cb_po_search.DisplayMember = "po_no";
cb_po_search.DataSource = dt;
sc.Close();
}
}
You need to use a LEFT OUTER join here instead of an INNER join
string strQry ="SELECT POMain.po_no FROM POMain INNER JOIN Shipping ON POMain.po_no = Shipping.po_no WHERE Shipping.invoice IS NULL";
And you need to add another condition to the WHERE clause at the end:
AND POMain.po_no = " + ID
Having said that, you would be much better off using a stored procedure instead of trying to form an inline query.

Mysql inner join column with spaces

I have 2 tables which are the customers table and orders table.
Basically my problem is that it always give me an error which is 'unknown field list'.
I have tried in phpmyadmin XAMPP it works the only problem is that when I use it in VS studio c# it gives me an error.
I'm confused the back ticks '`' don't work but the back ticks work on localhost.
Please help me.
This is my sql syntax:
SQL = "SELECT o.`Order ID`, o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.`Order ID` = c.`Order ID`
WHERE c.`Customer ID` = '" + cust_id + "'";
cmd.Connection = dbCon;
cmd.CommandText = SQL;
rdr= cmd.ExecuteReader();
dt.Load(rdr);
Have tried deleting and retyping the ` around the column names incase it didnt copy correctly. Also try putting a # before the string so.
SQL = #"<the sql>";
this works on mysql xampp
MySqlConnection sqlConnection = new MySqlConnection(#"Server=localhost;Database=test;");
var sql = #"SELECT o.`Order ID`, o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.`Order ID` = c.`Order ID`
WHERE c.`Customer ID` = 1";
sqlConnection.Open();
MySqlCommand sqlCommand = new MySqlCommand(sql,sqlConnection);
sqlCommand.ExecuteNonQuery();
sqlConnection.Close();
Columns with spaces in their name should be enclosed in square brackets.
Try
SQL = "SELECT o.[Order ID], o.Description, o.Amount
FROM tbl_orders AS o
INNER JOIN tbl_customers AS c ON o.[Order ID] = c.[Order ID]
WHERE c.[Customer ID] = '" + cust_id + "'";
cmd.Connection = dbCon;
cmd.CommandText = SQL;
rdr= cmd.ExecuteReader();
dt.Load(rdr);
http://tinyurl.com/qcf45vf
What is the use of the square brackets [] in sql statements?

SqlCommand - Select multiple rows and INSERT them into table

Hello I'm trying to SELECT multiple rows from table and INSERT them into another I thought that it can be done as following:
This part should select multiple rows:
string sqcom = "SELECT text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='"+klientClass.Rocnik()+"'";
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
This is how I try to INSERT selected rows from SqlCommand sc:
string sqlcom2 = "INSERT INTO zajsluz(akce,text,castka,rocnik) values (#akce,#text,#castka,#rocnik)";
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#akce", klientClass.Rocnik());
sc2.Parameters.AddWithValue("#text", ); // I dont know how to define this parameter according to what was selected in SqlCommand sc
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();
Now I'm wondering hwo can I insert into "#text" (sc2) parameter values from SqlCommand "sc" would you please help me solve this out?
Thanks in advance
Edit: ยจ
this is what I tried:
DataSet dt2 = new DataSet();
SqlDataAdapter SDA2 = new SqlDataAdapter("SELECT text,castka FROM zajsluz WHERE akce='" + tentoradek + "' and rocnik='" + klientClass.Rocnik() + "'", spojeni);
SDA2.Fill(dt2);
spojeni.Close();
string sqlcom2 = "INSERT INTO zajsluz(akce,text,castka,rocnik) values (#akce,#text,#castka,#rocnik)";
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#akce", zakce.Text);
sc2.Parameters.AddWithValue("#rocnik", klientClass.Rocnik());
sc2.Parameters.AddWithValue("#text", dt2.Tables[0].Columns["text"]);
sc2.Parameters.AddWithValue("#castka", dt2.Tables[0].Columns["castka"]);
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();
You can directly use insert into & select combination
string sqcom = "INSERT INTO zajsluz(akce,text,castka,rocnik) SELECT rocnik,text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='" + klientClass.Rocnik() + "'"
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
I would try to do this in a single statement if that is possible, i.e. you aren't doing anything to the data in between the two statements.
string sqlcom = "INSERT INTO zajsluz(akce,text,castka,rocnik) SELECT akce,text,castka,rocnik FROM zajsluz WHERE akce='"+tentoradek+"' and rocnik='"+klientClass.Rocnik()+"'";
SqlCommand sc = new SqlCommand(sqcom,spojeni);
spojeni.Open();
sc.ExecuteNonQuery();
spojeni.Close();
Another option would be to use a SQL DataSet/DataTable, which allows you to query and return from SQL an entire table, or a set of rows, that you can then update, delete or insert into. It's described in the following MS article: http://support.microsoft.com/kb/326009/en
This summary answer for your question:
StringBuilder query = new Stringbuilder();
query.AppendLine("INSERT INTO zajsluz(akce,text,castka,rocnik) ");
query.AppendLine("(SELECT #akce, text, castka, #rocnik");
query.AppendLine("FROM zajsluz WHERE akce=#Tentoradek");
query.AppendLine("AND rocnik=#rocnik)");
SqlCommand sc2 = new SqlCommand(sqlcom2, spojeni);
sc2.Parameters.AddWithValue("#Tentoradek", tentoradek);
sc2.Parameters.AddWithValue("#akce", zakce.Text);
sc2.Parameters.AddWithValue("#rocnik", klientClass.Rocnik());
spojeni.Open();
sc2.ExecuteNonQuery();
spojeni.Close();

Copy datarow from one table to another similar table in different database c#

I have tableA in database1 and tableA in database2 both have similar number of columns and names basically same tables. But both have different data in them. I am trying to get a row from database1/tableA and insert it into database2/tableA.
This is how i am thinking of doing it:
SqlConnection conn = new SqlConnection("database1")
SqlCommand cmd = new SqlCommand("Select * from tableA where id = 1");
connection.Open()
SqlDataReader reader = cmd.ExecuteReader();
if(reader !=null )
var data = reader;
connection.Close();
Then i do the same above steps open a new connection and try to insert data variable values to tableA in database2.
Is this right approach? Is there a better way to do this?
I would do this with an inter-DB query. In MSS 2005/2008, you can "link" two servers together as long as they can see each other. Once that's done, you can refer to the linked database's table by specifying the linked server name, database, schema owner and table in dot notation. That would allow an INSERT SELECT:
INSERT INTO TableA --in database1
{
/*columns*/
}
SELECT /*columns*/ from remoteServer.database2.dbo.TableB
WHERE /*dupe-checking, other conditions*/
If the two databases are on the same server, you don't even have to link; just preface the table on the remote database with the DB name and schema owner (or if it's the default "dbo", use two dots between db name and table name.
you can use this query instead
INSERT INTO DATABASE2.dbo.TABLEA T1
SELECT * FROM DATABASE1.dbo.TABLEA T2
WHERE T2.ID = 1
The following c#, code should work, provided both databases are in the same server.
SqlConnection conn = new SqlConnection("Enter Connection String of DB, in which you insert the records.(in ur example it is,DATABASE2)");
string cmdText=#"INSERT INTO DATABASE2.dbo.TABLEA T2
SELECT * FROM DATABASE1.dbo.TABLEA T1
WHERE T1.ID = 1";
SqlCommand cmd = new SqlCommand(cmdText, conn);
cmd.ExecuteNonQuery();
string connection_String = #""; //your connection string
try
{
using (SqlConnection con = new SqlConnection(connection_String))
{
string sql = "INSERT INTO table_copy_to " +
"(column1, column2, column3 ... columnn) " +
"SELECT column1, column2, column3 ... column FROM table_copy_from";
con.Open();
using (SqlCommand cmd = new SqlCommand(sql, con))
{
int rowEffected = cmd.ExecuteNonQuery();
if (rowEffected > 0)
{
Console.WriteLine("Excuted Successfully ...");
}
else
{
Console.WriteLine("Some problem occur");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Exception : " + ex);
}

Categories