I executed the following statement but it only updates the price rows of all except Assasin creed (blank value). Also, the prices in the other rows in my table which are not defined below ironically was cleared (blank value). It seems to be working normally if i update 2 products though. What could be wrong?
(line breaks for display-wrapping only)
"UPDATE Products SET Price = IIf(Product = 'Crysis Wars'," +
CrysisWarsInput.Text +
", IIf(Product = 'Far Cry 2'," + FarCry2Input.Text +
", IIf(Product = 'Day of Defeat Source'," + DODSourceInput.Text +
", IIf(Product = 'GTA 4'," + GTA4Input.Text +
", IIf(Product = 'Asassins Creed'," + AssassinsCreedInput.Text + ")))))";
Maybe because you mis-spelt "Assasins Creed"?
Either set a WHERE clause, or add Price as the default value in the last IIF
"UPDATE Products SET Price = " +
" IIf(Product = 'Crysis Wars'," + CrysisWarsInput.Text +
", IIf(Product = 'Far Cry 2'," + FarCry2Input.Text +
", IIf(Product = 'Day of Defeat Source'," + DODSourceInput.Text +
", IIf(Product = 'GTA 4'," + GTA4Input.Text +
", IIf(Product = 'Assasins Creed'," + AssassinsCreedInput.Text + ", Price)))))";
the other rows in my table which are not defined below
That's what a WHERE clause is for, to restrict which records to update.
"UPDATE Products SET Price = " +
" IIf(Product = 'Crysis Wars'," + CrysisWarsInput.Text +
", IIf(Product = 'Far Cry 2'," + FarCry2Input.Text +
", IIf(Product = 'Day of Defeat Source'," + DODSourceInput.Text +
", IIf(Product = 'GTA 4'," + GTA4Input.Text +
", " + AssassinsCreedInput.Text + ")))) +
" WHERE Product in ('Crysis Wars','Far Cry 2','Day of Defeat Source'," +
" 'GTA 4','Assasins Creed')";
You can also use a SWITCH statement instead of multiple IIFs.
Re assasins creed - probably a typo. Look very carefully at the value in the cell and in your query - for example, is it assassin vs assassins?
Re the others (not in the query); you need to add a "where" clause, otherwise it applies to every row in the table; that is how SQL works... I'm guessing an IN filter would be best here. Fr example
where Product in ('some title', 'another title', ...)
Related
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.
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.
Firstly apologies for the woolly subject title, its hard to put this one into words.
So…with that in mind I’ve attached a database relationship diagram (see below) which will hopefully explain it much more concisely.
We have inherited a large database (and therefore have no ability to change/rationalise it, more’s the pity!) which has a troublesome ‘loop’ of 4 tables that have a couple of different many to many relationships within.
I need to be able to get out the Court’s name, full address, and general notes, all of which every court will only have one of, followed by the Contact details which are divided into two groups (general and specific contact points) which could contain one or more listings dependent on the court. I need this to appear in the format below:
Abergavenny Magistrates' Court
Abergavenny
NP7 5DL
This court is open for hearings only. Additional Court Notes….
Contacts
Switchboard: 01633 64xxxx
Fax: 01633 64xxxx
Service 1: 01633 64xxxx
Service 2: 01633 64xxxx
Contact Name 1 - Acting Court Manager: 01633 64xxxx
Contact Name 2 - Acting Office Manager: 01633 64xxxx
Contact Name 3 - Acting List Officer: 01633 64xxxx
Contact Name 4 - Justices' Clerk: 01633 64xxxx
I posted on StackOverflow yesterday to find out how to correctly write the SQL query and ASP.NET C# code for one many-to-many relationship. For simplicity’s sake the info I provided was very much paraphrased and basically contained only half of the loop you see above. However I’ve since failed in my attempt to apply the same principles to the full loop.
The SQL query (which works for the first half of the loop, i.e. to provide the court address details and a list of the specific contact points) looks like this:
string myQuery =
"SELECT C.court_id, court_name, court_addr1, court_town_name, court_county_name, " +
"court_country_name, court_addr_pcode, court_addr_dx, court_code, court_note, " +
"court_contacts_name, court_contacts_no, CCT.court_contact_type_desc " +
"FROM court C " +
"JOIN court_addr CA ON C.court_addr_id = CA.court_addr_id " +
"JOIN court_town CT ON CA.court_town_id = CT.court_town_id " +
"JOIN court_county CC ON CT.court_county_id = CC.court_county_id " +
"JOIN court_country CCO ON CC.court_country_id = CCO.court_country_id " +
"JOIN court_contacts CCON ON C.court_id = CCON.court_id " +
"JOIN court_contact_type CCT ON CCON.court_contact_type_id = CCT.court_contact_type_id " +
"WHERE C.court_id = '25' " +
"ORDER BY C.court_id";
Whilst the C# looks like this:
if (myDataReader.HasRows)
{
string last_id = string.Empty;
while (myDataReader.Read())
{
string court_id = myDataReader["court_id"].ToString();
string court_name = myDataReader["court_name"].ToString();
string court_addr = myDataReader["court_addr1"].ToString();
string court_town = myDataReader["court_town_name"].ToString();
string court_county = myDataReader["court_county_name"].ToString();
string court_country = myDataReader["court_country_name"].ToString();
string court_pcode = myDataReader["court_addr_pcode"].ToString();
string court_dx = myDataReader["court_addr_dx"].ToString();
string court_code = myDataReader["court_code"].ToString();
string court_note = myDataReader["court_note"].ToString();
string court_contact_name = myDataReader["court_contacts_name"].ToString();
string court_contact_desc = myDataReader["court_contact_type_desc"].ToString();
string court_contact_no = myDataReader["court_contacts_no"].ToString();
if (last_id != court_id) {
Response.Write("<strong>" + court_name + "</strong><br>" + court_addr +
"<br>" + court_town + "<br>" + court_county + "<br>" +
court_country + "<br>" + court_pcode + "<br><br>" +
court_dx + "<br><p>Court code " + court_code + "</p><p>" +
court_note + "</p>" + court_contact_name + " - " +
court_contact_desc + ": " + court_contact_no + "<br>");
} else {
Response.Write("<br>" + court_contact_name + " - " + court_contact_desc +
": " + court_contact_no + "<br>");
}
last_id = court_id;
}
}
Following the same logic in the SQL query I’ve tried to add an additional SELECT parameter of court_contacts_general_no and a couple of extra JOIN lines to bring in the court_contacts_general table (see below), however, this produces errors along the lines of ‘The correlation name CCG is specified multiple times in a FROM clause’ or just goes completely blank if the 2nd correlation name is removed.
"JOIN court_contacts_general CCG ON C.court_id = CCG.court_id " +
"JOIN court_contacts_general CCG ON CCT.court_contact_type_id = CCG.court_contact_type_id " +
Whilst in the C# I’ve added a new string for court_contact_general_no and tried creating another if/else loop based on writing the response received from this new variable.
Either way, all I’m getting is a big blank page or the SQL related errors above.
Any ideas?
Thanks in advance for all/any help.
You'll need to use different table name aliases in order to join the same table more than one time in a single query
JOIN court_contacts_general CCG1
JOIN court_contacts_general CCG2.. etc
I'd recommend naming the tables something more relevant to what data is being returned though in that case
It's certainly not elegant (no doubt there's a much better way of writing it!) but I've managed to work out a solution to the problem by writing a second SQL query and opening a second Sqlconnection directly after the first one has closed to tag on the second batch of contacts.
SQL query:
string myQuery2 =
"SELECT C.court_id, court_contacts_name, court_contacts_no, court_contact_type_desc " +
"FROM court C " +
"JOIN court_contacts CCON ON C.court_id = CCON.court_id " +
"JOIN court_contact_type CCT ON CCON.court_contact_type_id = CCT.court_contact_type_id " +
"WHERE C.court_id = '" + court_id_no + "' " +
"ORDER BY C.court_id";
C# code:
myDataReader.Close();
connection.Close();
SqlConnection connection2 = new SqlConnection(connStr);
SqlCommand myCommand2 = new SqlCommand(myQuery2, connection2);
SqlDataReader myDataReader2;
connection2.Open();
myDataReader2 = myCommand2.ExecuteReader();
if (myDataReader2.HasRows) {
string last_id = string.Empty;
while (myDataReader2.Read()) {
string court_id = myDataReader2["court_id"].ToString();
string court_contact_desc = myDataReader2["court_contact_type_desc"].ToString();
string court_contact_name = myDataReader2["court_contacts_name"].ToString();
string court_contact_no = myDataReader2["court_contacts_no"].ToString();
if (string.IsNullOrWhiteSpace(court_contact_no)) {
court_contact_no = generic_contact_no;
}
if (last_id != court_id) {
Response.Write(court_contact_name + " - " + court_contact_desc + ": " + court_contact_no + "<br>");
} else {
Response.Write(court_contact_name + " - " + court_contact_desc + ": " + court_contact_no + "<br>");
}
last_id = court_id;
}
}
As I say, not pretty but the important thing is it works.
Okay, so in the past few weeks I've probably written about 40 select statements. So, I know how to do it. And I've just written another one, but this time I need to use ComboBox values to match against, and it keeps resulting in the names of the column (the right column, mind you), instead of what's inside the column.
string st = "SELECT '" + txtchange.Text + "'
FROM mysql_9269_dbase." + pages.Text + "";
MySql.Data.MySqlClient.MySqlCommand cd = new MySql.Data.MySqlClient.MySqlCommand(st, msc);
cd.CommandType = CommandType.Text;
MySql.Data.MySqlClient.MySqlDataReader msdr = cd.ExecuteReader();
while(msdr.Read())
{
txt.Text = msdr[0].ToString();
}
Now, why is it returning the column name instead of the content of that column?
Lose the single quotes.
Change
"SELECT '" + txtchange.Text + "' "
to
"SELECT " + txtchange.Text + " "
In sql you can do it like this.
string query = "Execute("+"'SELECT " + txtchange.Text + " FROM mysql_9269_dbase." + pages.Text + "')";
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.