How do I run an SQL update query using a like statement - sql

I am trying to update a field in a table using an SQL update query where there is a like statement referencing a value in another table. They syntax unfortunately is not working. Below is my code. In short, I am trying to put a '1' in the field 'Query07ParolaChiave' in the table 'tblSearchEngine01' when the value located in table 'tblsearchengine07' is present in the field 'tblMasterListOfEventsNotes' located in the table 'tblSearchEngine01'. I think my code is almost complete but there is a syntax issue which i cant find.
st_sql = "UPDATE tblSearchEngine01, tblSearchEngine07 SET tblSearchEngine01.Query07ParolaChiaveSelect = '1' WHERE ((([tblSearchEngine01].[tblMasterListOfEventsNotes]) Like " * " & [tblsearchengine07].[ParolaChiave] & " * "))"
Application.DoCmd.RunSQL (st_sql)

I suggest you 2 solutions :
This one is using EXISTS functions, and will check for each row in tblSearchEngine01 if there is a matching value in tblsearchengine07
UPDATE
tblSearchEngine01
SET
tblSearchEngine01.Query07ParolaChiaveSelect = '1'
WHERE
EXISTS (SELECT 1
FROM tblsearchengine07
WHERE [tblSearchEngine01].[tblMasterListOfEventsNotes] Like '*' & [tblsearchengine07].[ParolaChiave] & '*')
This one is more performant because it uses JOIN
UPDATE
tblSearchEngine01
INNER JOIN tblsearchengine07
ON [tblSearchEngine01].[tblMasterListOfEventsNotes] Like '*' & [tblsearchengine07].[ParolaChiave] & '*'
SET
tblSearchEngine01.Query07ParolaChiaveSelect = '1'
I read something like in ADO/VBA, you have to use % instead of * as the wildcard.
You can have more information on wildcard and LIKE comparator here
UPDATE
Why the '1' after select in your first solution?
EXISTS (SELECT 1 ... is better for performance because it return only the number 1 instead of fields, anyway EXISTS just stop the excecution after 1 element found.
'Performant' means more consuming in regards to space and memory?
JOIN is more performant in term of time of execution, RDBMS are far better at joining tables than using subquery, in some rare case, it's more interesting to use the 1st solution.
Also, any initial thoughts as to why my original solution (coming straight from an Access Query which works) does not function?
I cannot really know but perhaps it's because of " * ", because you are saying SPACE + * + SPACE + VALUE + SPACE + * + SPACE. For ex : 'John' LIKE ' John '
May be with "*" instead of " * " could solve it...
I have no other track, I'm not Access sql developper, I usually play around Sql server/Oracle/mySql, hope it helped. ;)

Try to change your like this way:
... Like '*" & tblsearchengine07.parolachiave & "*'))"

The like statement go into the WHERE clause.
If you do want to use LIKE without you care about caps letters, then you can use it like this:
LIKE COLUMN_NAME = '%WhatYouLike%'

My suggestion is:
Use a table variable (#Table) with a unique/primary key coming from the table to be updated.
SELECT all the data to be updated (you can add the like statement here) and then INSERT that in the created table variable.
Construct the UPDATE statement with an INNER JOIN to the table variable matching with the unique/primary key.
I know this may take a lot of steps but believe me these are more efficient than using a black list approach.

Related

ACCESS update with subquery

I have a table like this:
Now I'm trying to write in the column "SUMAMOUNT" of the table the sum of amount per "CODE" and "IBAN" but i can't reach this.
I'd want something like this:
I'm using this query but it doesn't work:
update tabella
set sumamount = (select sum(t2.amount)
from tabella as t2
where t2.code = tabella.code and t2.iban = tabella.iban
);
The precedent query gives me this result:
Can you help me? I'm using MS ACCESS.
Thank you in advance!
EDIT: Screenshot of the error:
I can't even try to run it because he ask me to save it. When I try to save, access gives me this error.
Consider domain aggregate, DSum, which allows an updateable query. Below assumes code and iban are text types and therefore requires single quote enclosures.
UPDATE tabella t
SET t.sumamount = DSUM("amount",
"tabella",
"code = '" & t.code & "' AND iban = '" & t.iban & '");
(By the way, best practice in databases is to avoid saving calculations in tables. Save resources and simply run queries on data as needed.)

Use a parameter in SSRS for table_name

I have scoured the internet for options and the only one I have found that can do it is by using a $Proc however I am trying to avoid that.
I would think it would be pretty simple to use a parameter to select a different table depending on what the user chooses from a drop down.
Here it is:
- There are two tables the report needs to use,
* some_table_CY (current year table)
* some_table_STLY (same time last year table)
So I created a parameter that gives the user the option to select "Current_Year" or "Last_Year", depending on which one the user chooses the parameter would then be used in the select statement, something like this: "SELECT * FROM :pReportVersion"
However, it is not working. I need it to do this, not using a union since unioning these two tables causes HUGE performance issues and the query takes more than 4 hours to run which is not acceptable for a report that users need on request.
(This is querying oracle)
Use the Dataset expression and set it to:
="SELECT * FROM " & Parameters!ReportVersion.Value
For longer queries you may need to wrap each line with quotes, append with an ampersand and add a line feed:
="SELECT * " & VBCLRLF &
"FROM " & Parameters!ReportVersion.Value & VBCRLF &
"WHERE FIELD1 > 10 " & VBCRLF &
"AND FIELD2 = 'YES' "
you can still use the union..
Say you have a parameter called #year
set the available values to the following (specify values)
current year for label and 1 for value
last year for label and 2 for value
Then your dataset can be something like this:
select * from some_table_CY
where #year = 1
union all
select * from some_table_LY
where #year = 2

Dynamically create sql where condition on textbox entry

I am working on a C# desktop application. I want to create a search functionality. Now the problem is that i am using around 8 textboxes. Different permutations of textboxes could be populated and the resulting 'sql where' condition should only include those textboxes values which are not null. Now one pathetic way is to use a zillion 'if and else' which obviously is laborious. Any other way to do this?
You need just one query with filled WHERE to use all parameters like this
select ...
from ...
WHERE
(firstNameColumn=:firstNameParam or :firstNameParam is null)
AND (lastNameColumn=:lastNameParam or :lastNameParam is null)
AND (...)
I would like to make a point of first checking is the paramtere null, then use it to compare with column values.
Since you are generating query in C#, try old-Chinese approach from Ming period of using default condition where 1=1 just to avoid checking did you already had first condition :)
string query = "select ... from ... join ... on ... where 1=1";
//suposedly you have value of one search box in variable called "item_name"
if(string.IsNullOrWhiteSpace(item_name) == false)
{
query += " and Order_Line.Name ='" + item_name + "'";
}
and so on for other fields.
What you are trying to do in order to avoid ifs is not really a good approach. Look at this:
string query = " select ... where Order_Line.Name = '" + item_name + "'";
What will be the resulting string if item_name is actually null?
EDIT: the resulting query would be
where Order_Line.Name = '' or Order_Line.Name is null
which is not what you want. You want every row if that search field is empty, menaing it shouldn't have anu effect on search. That's why you need condition to see will you include this column in where clause in the first place.

Updating a table in MS_Access using SQL

I have a few databases and I need to insert a string value in front of some of the values. I have the following code:
UPDATE DB_AlarmTest SET DB_AlarmTest.Address = "DB40," & [Address]
WHERE DB_AlarmTest.Address
NOT LIKE '%DB40%';
I dont want my adresses to come out like this: "DB40,DB40,DB40,2.0" If i execute the query more than once, so I added the " NOT LIKE '%DB40%' " part
Can someone tell my why this is not working?
Thanks in advance!
With the usual ANSI options in MS Access, the wildcard is *, not %, so:
UPDATE DB_AlarmTest
SET DB_AlarmTest.Address = "DB40," & [Address]
WHERE DB_AlarmTest.Address Not Like "*DB40*"

Matching text string on first letter in SQL query

SAMPLE CODE:
Dim sql As String = "SELECT * FROM " + tblName + " WHERE needsTranslation = 'True' AND dataText LIKE " & "'" & alpha & "%" & "'" & " ORDER BY dataText;"
da = New SqlDataAdapter(sql, strConnection)
OP:
I would like to create a SQL query that returns all records when the first letter of a string matches my variable. I am coding this in an ASP.net code behind page in vb.net.
SELECT * FROM " + tblName + " WHERE textData = ' & alpha & "
In this exmample textData is a string of text and alpha is a single letter a through z or A through Z.
I don't need the criteria to be case sensitive, but I do need only the first letter of textData to match alpha.
I have tested the LIKE comparator and it does not return all records that begin with alpha.
What is the best way to do this? Any and all help will be appreciated.
thanks again,
The LIKE operator is what you'd want to use, but you have to use the % wildcard character like so:
SELECT * FROM MyTable WHERE textData LIKE 'a%'
SQL has sub-string operator SUBSTR() or SUBSTRING()
select * from tableName where substr( textData ) in ( 'A', 'B', 'C', ... );
I couldn't add to the comments on one of the other posts, but I'll strongly second the need to use a parameterized query for these reasons (you can include usage of the like operator with the wildcard % like the other answer correctly summarized to answer your question):
It will protect you from making mistakes with single quotes, especially if the user enters a search string that includes them
(they will cause your query to fail).
It protects you from SQL injection exploits. Example, a user were able to input the value of the variable "alpha" in the above
example they could enter something like:
'; DELETE FROM ;
If the user you were using had excessive database rights, they could
wreak all kinds of havoc (or they could potentially get access to
data they shouldn't have access to).