update merge query with where clause in sql - c#

note: i m importing data from sql sheet. and after this i want to insert data in a table but when it finds same ContractNo (contract number) it will update the data and when it finds different ContractNo ( contract number) it will insert as a new record
but my merge query is not working with where statement.
string mergeSql = "merge into " + tableName + " as Target " +
"using Ro_Consumers_Temp as Source " +
"on " +
"Target.ContractNo=Source.ContractNo " +
"when not matched then " +
"insert values (Source.Ronumber,Source.ContractNo,Source.BusinessPartner,Source.ContractAccount,Source.IBC,Source.Portion,Source.MRU,Source.Installation,Source.MeterNo,Source.LegacyNumber,Source.ConsumerNo,Source.ConsumerName,Source.Address,Source.Tariff,Source.ROAgent,Source.IBCName,Source.CD,Source.Batch,Source.JasbNumber,Source.SheetNo, Source.ContactName,Source.ContactNumber,Source.FOName,Source.[Address&LandMark],Source.NatureOfBusiness)" +
"when matched then update set Batch = Source.Batch, JasbNumber = Source.JasbNumber Where Target.Batch=Source.Batch;";

Replace your WHERE clause with additional WHEN MATCHED clause condition:
string mergeSql = "merge into " + tableName + " as Target " +
"using Ro_Consumers_Temp as Source " +
"on " +
"Target.ContractNo=Source.ContractNo " +
"when not matched then " +
"insert values (Source.Ronumber,Source.ContractNo,Source.BusinessPartner,Source.ContractAccount,Source.IBC,Source.Portion,Source.MRU,Source.Installation,Source.MeterNo,Source.LegacyNumber,Source.ConsumerNo,Source.ConsumerName,Source.Address,Source.Tariff,Source.ROAgent,Source.IBCName,Source.CD,Source.Batch,Source.JasbNumber,Source.SheetNo, Source.ContactName,Source.ContactNumber,Source.FOName,Source.[Address&LandMark],Source.NatureOfBusiness)" +
"when matched " +
"and Target.Batch=Source.Batch " + // <<< Move the clause here
"then update set Batch = Source.Batch, JasbNumber = Source.JasbNumber";
See MERGE statement documentation for more info.

Related

How to combine two SQLite statements running in C#?

I have these two statements:
db2.Execute(" UPDATE CLICKHISTORY SET " +
" DAYOFYEAR = " + dayOfYear + " , " +
" YEAR = " + year + " , " +
" MONTH = " + month + " , " +
" DAY = " + day + " , " +
" BTNACOUNT = BTNACOUNT + 1 WHERE YYMMDD = " + yymmdd );
db2.Execute(" INSERT INTO CLICKHISTORY " +
" (YYMMDD,DAYOFYEAR,YEAR,MONTH,DAY,BTNACOUNT) " +
" VALUES ( " +
yymmdd + " , " +
dayOfYear + " , " +
year + " , " +
month + " , " +
day + " , " +
"1) WHERE changes() = 0");
What I would like to do is to check if changes() = 0 in the first statement before running the second statement.
Can anyone tell me how I can group together these two statements in to one so I can check the value of changes()?
Assuming db2 is of type SQLite.SQLiteConnection, you can use the return value of the Execute method to find out the number of affected rows - something like:
int rowsAffected = db2.Execute("UPDATE...");
if (rowsAffected == 0) {
rowsAffected = db2.Execute("INSERT...");
}
In general, you can combine sqlite statements using semicolon ;.
But as I understand, the real question here is: How to conditionally insert values in SQLite?
You cannot use WHERE with INSERT INTO table VALUES(...), but use can use INSERT INTO table SELECT ... syntax instead and add a WHERE clause to select.
Example
Let's say I have a simple table: scores (name varchar(20), score int). I want to update a row or insert a new one if there's nothing to update yet.
var name = "my team";
var sql = $"update scores set score = score+1 where name = '{name}';"
+ $"insert into scores(name, score) select '{name}', 0 where changes() = 0" ;
var cmd = new SQLiteCommand(sql, conn);
cmd.ExecuteNonQuery();
Depending on the driver you use, the C# methods used may differ - I'm using System.Data.Sqlite here.
You may also want to taka look at how to do Upsert in SQLite.

MySqlDataAdapter Update table that uses Inner Join

I'm tring to add the Insert, Update and Delete commands to a MySqlDataAdapter which has the data added to it with the command:
//iec211.4521studenti
string lv_sObsTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTable = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti'";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObsTable + " o INNER JOIN " + lv_sStudTable + " s USING (idStudent) ORDER BY s.nume ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
I've serched for an answer and I've found two possible solutions for UPDATE, but both of them give me an error:
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
//VERSION 1
string lv_sCommand = "UPDATE o SET s.idStudent=#idStudent, o.observatie=#observatie FROM " + lv_sObsTB + " AS o INNER JOIN " + lv_sStudTB + " s ON o.idStudent=s.idStudent ";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
//VERSION 2
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET " + "idStudent=#" + lv_sStudTB + ".idStudent, observatie=#observatie WHERE idObservatie=#idObservatie AND " + lv_sObsTB + ".idStudent IN (SELECT " + lv_sStudTB + ".idStudent FROM " + lv_sStudTB + ")";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#" + lv_sStudTB + ".idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
The error message for the first version is : "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM iec211.4521observatii ASS o INNER JOIN iec211.4521studenti s ON o.id' at line 1"
The error message for the second version is:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.4521studenti'.idStudenti, observatie='test' WHERE idObservatie=1 ANDiec211.' at line 1"
I don't know how to use the MySQL commands in combination with MySqlCommand and MySqlDataAdapter.
Until now I've used the following command to obtain data for my table:
string lv_sObservatiiCommand = "SELECT * FROM `" + mv_sDatabase + "`.`" + mv_sGroup + "observatii` ORDER BY idStudent ASC";
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
In combination with MySqlCommandBuilder to get the update command and the parameters that needed to be setted:
lv_sqlCommandBuilder = new MySqlCommandBuilder(mv_dtAdapterObservatii);
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommandBuilder.GetUpdateCommand();
Can someone please explain to me how to correctly add the insert, update and delete commands to a MySqlDataAdapter that contains an INNER JOIN between 2 tables ?
I know that each table must be in a different data adapter, and they are. The "4521studenti" table is inside "mv_dtAdapterStudenti", which is not included in the code above.
Thank you for the help and I hope this won't be considered as a bad post. :)
Okey. I think I've figured it out.
This is the SELECT command for 4521observatii:
string lv_sStudent = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sObservatii = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
string lv_sObservatiiCommand = "SELECT o.idObservatie, o.idStudent, s.nume, o.observatie, o.lastUpdate FROM " + lv_sObservatii + " o INNER JOIN " + lv_sStudent + " s USING (idStudent) ORDER BY s.nume ASC";
// Read data from the server for the current table and add it to the DataSet
mv_dtAdapterObservatii = new MySqlDataAdapter(lv_sObservatiiCommand, mv_sqlConnection);
mv_dtAdapterObservatii.Fill(mv_dsTables, lv_sCurrentTable);
And this is the code for the UPDATE command, inside a different method:
// `iec211`.`4521observatii`
string lv_sObsTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "observatii`";
// `iec211`.`4521studenti`
string lv_sStudTB = "`" + mv_sDatabase + "`.`" + mv_sGroup + "studenti`";
string lv_sSelectStudenti = "(SELECT idStudent FROM " + lv_sStudTB + " WHERE idStudent=#idStudent)";
string lv_sCommand = "UPDATE " + lv_sObsTB + " SET idStudent="+ lv_sSelectStudenti + ", observatie=#observatie WHERE idObservatie=#idObservatie";
MySqlCommand lv_sqlCommand = new MySqlCommand(lv_sCommand);
lv_sqlCommand.Parameters.Add("#idStudent", MySqlDbType.Int16, 10, "idStudent");
lv_sqlCommand.Parameters.Add("#observatie", MySqlDbType.VarChar, 255, "observatie");
lv_sqlCommand.Parameters.Add("#idObservatie", MySqlDbType.Int16, 10, "idObservatie");
mv_dtAdapterObservatii.UpdateCommand = lv_sqlCommand;
mv_dtAdapterObservatii.UpdateCommand.Connection = mv_sqlConnection;
The idea is that when I use INNER JOIN I bring data from two different tables and put them together. When I used the UPDATE command, the program didn't know which table he was using and gived those errors.
So I thought what if I update the values of 4521observatii and for the column that is used as FOREIGN KEY I assign the value from 4521studenti.
I know it's like "Tell me your name so I can tell you your name.", but it worked for me.
I hope this will help others and you have a better and cleaner solution, pleas tell me :)

Syntax error in FROM clause. in Inserting records from ms access into another ms access database

This is my code
string stR = "INSERT INTO CHECKINOUT (USERID,CHECKTIME,CHECKTYPE,VERIFYCODE,SENSORID,WorkCode) " +
" SELECT a.USERID,c.CHECKTIME,c.CHECKTYPE,c.VERIFYCODE,c.SENSORID,c.WorkCode " +
" FROM USERINFO a " +
" JOIN [MS Access;DATABASE=" + open.FileName + "].USERINFO b " +
" ON a.BadgeNumber=b.Badgenumber " +
" JOIN [MS Access;DATABASE=" + open.FileName + "].CHECKINOUT c " +
" ON b.USERID=c.USERID " +
" WHERE NOT EXISTS " +
" (SELECT a.USERID,c.CHECKTIME,c.CHECKTYPE,c.VERIFYCODE,c.SENSORID,c.WorkCode " +
" FROM USERINFO a " +
" JOIN [MS Access;DATABASE=" + open.FileName + "].USERINFO b " +
" ON a.BadgeNumber=b.Badgenumber " +
" JOIN [MS Access;DATABASE=" + open.FileName + "].CHECKINOUT c " +
" ON b.USERID=c.USERID)";
I got exception error "Syntax error in FROM clause"
Note: I already exported all ms access tables to ms sql 2000 database and this script is working fine with no error, but with ms access I receive this kind of error, This is the first time I'm using ms access as back end, this is an old program in my office that I need to fix error.
My first question is which FROM clause is failing. I would test each portion separately. Does the query work if you remove the WHERE NOT EXISTS clause? If so then the problem is in the subquery WHERE NOT EXISTS is referencing.

SQL C# WPF Query Expanded

I had a query answered here SQL Select All Without Values in Another Table.
I've just been asked to integrate the data from another database. This is what I have at the moment.
string _loanSubcontractor = TableNames.Default.LoansSubcontractors;
string _loanPacific = TableNames.Default.LoansPacific;
string _tools = TableNames.Default.Tools;
string _selectStatement = " SELECT [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code] ";
string _groupBy = " GROUP BY [Tools].[Type], [Tools].[Brand], [Tools].[Serial], [Tools].[Year], [Tools].[Code], [Tools].[Working] ";
string _searchItems = " ([Tools].Code LIKE #toolSerial OR [Tools].Serial LIKE #toolSerial) AND ([Tools].[Working] = 'True' OR [Tools].[Working] IS NULL) ";
SqlConnection myConnection = new SqlConnection(Connection.Default.ConnectionString);
//Checks the main tool information
myConnection.Open();
SqlCommand getTool = new SqlCommand(
_selectStatement + "FROM [" + _tools + "] LEFT OUTER JOIN [" + _loanSubcontractor + "] ON " +
_tools + ".code = [" + _loanSubcontractor + "].ToolCode FULL JOIN [" + _loanPacific + "] ON " + _tools + ".Code = " +
_loanPacific + ".ToolCode WHERE [" + _loanSubcontractor + "].ToolCode IS NULL AND [" + _loanPacific + "].ToolCode IS NULL AND (" + _searchItems + ")" +
"UNION " +
_selectStatement + " FROM [" + _loanSubcontractor + "] INNER JOIN " + _tools + " ON " + _tools + ".Code = [" + _loanSubcontractor + "].ToolCode " +
"INNER JOIN " + _loanPacific + " ON " + _loanPacific + ".ToolCode = " + _tools + ".Code " + _groupBy +
"HAVING (COUNT(" + _loanSubcontractor + ".ReturnDate) = COUNT(*) OR COUNT(" + _loanPacific + ".ReturnDate) = COUNT(*)) " +
" AND " + _searchItems, myConnection);
getTool.Parameters.Add("#toolSerial", SqlDbType.NVarChar).Value = "%" + toolSerial + "%";
What I have is two loan tables (one for employees and one for subcontractors) because the attribute names are different and the data types are also different. Essentially, I need to check that the tool is working, and the tool is not hired out in either of the loan tables (as shown by the return date being null). There may or may not be a loan in either of the tables.
Also, could someone provide me with a link that shows good formatting techniques for SQL within C#?
i sagest you use linq to SQL . this is a part of ADO.NET and you can use long query with 100 % acres and easy way
msdn.microsoft.com for linq to SQL
LINQ to SQL: .NET Language-Integrated Query for Relational Data
Simple LINQ to SQL in C#

How can you use parameterized statements with DB2 Text Search?

I've tried this:
select * from ourschema.mytable
where contains(mysearchablefield, #searchTerms) = 1;
Where #searchTerms was set to "search terms"
Unfortunately, it only produced an error:
ERROR [42610] [IBM][DB2/NT] SQL0418N A statement contains a use of a parameter marker that is not valid. SQLSTATE=42610
Is there a way to use parameterized queries for text search with DB2? If not, is there a document which describes the syntax in detail for manual (ugh) escaping of the search terms (quotes, etc)?
Instead of #field you need to use "?". Everything is basically the same.
Okay, here is a live code sample.
sqlStmt = "SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 1 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE = 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE1 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE1 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE1 AND #TO_COMPLAINT_DATE1 " +
statusQry +
"UNION " +
"SELECT COMPLAINT_NUMBER, VIOLATION_NUMBER, COMMON_ADDRESS_KEY, " +
"DEPT_CODE, DEPT_CODE_DESC, DIVISION_CODE, DIVISION_CODE_DESC, " +
"EMPLOYEE_NAME, COMPLAINT_CODE, COMPLAINT_CODE_DESC, COMPLAINT_DATE, " +
"COMMON_ADDRESS_OWNER, RESOLUTION_CODE, 2 AS SORTORDER " +
"FROM QMFILES/NVMASTP " +
"WHERE VCLOSEDATE <> 0 AND " +
"DEPT_CODE LIKE #DEPT_CODE2 AND " +
"DIVISION_CODE LIKE #DIVISION_CODE2 AND " +
"COMPLAINT_DATE BETWEEN #FROM_COMPLAINT_DATE2 AND #TO_COMPLAINT_DATE2 " +
statusQry +
"ORDER BY DEPT_CODE, DIVISION_CODE, COMPLAINT_CODE, SORTORDER";
iDB2Command cmd = new iDB2Command(sqlStmt, conn);
conn.Open();
cmd.DeriveParameters();
conn.Close();
cmd.Parameters["#DEPT_CODE1"].Value = dept;
cmd.Parameters["#DIVISION_CODE1"].Value = serviceArea;
cmd.Parameters["#DEPT_CODE2"].Value = dept;
cmd.Parameters["#DIVISION_CODE2"].Value = serviceArea;
cmd.Parameters["#FROM_COMPLAINT_DATE1"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE1"].Value = Convert.ToDecimal(toDateString);
cmd.Parameters["#FROM_COMPLAINT_DATE2"].Value = Convert.ToDecimal(fromDateString);
cmd.Parameters["#TO_COMPLAINT_DATE2"].Value = Convert.ToDecimal(toDateString);
I hope this helps you out more.

Categories

Resources