I am attempting to update several values in a table based on several conditions. If a column (let's call it "name") contains some set of strings, I would like to change the name to something else. For example, if name contains two consecutive a's, like "aa", I would like to change it to just "A".
Here is my query that is currently not working:
UPDATE table
SET name = CASE name
WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
I know it is a non-sensical example, but I'm not great with coming up with those on the spot. The error I am currently getting is:
"No matching signature for operator CASE for argument types: STRING, BOOL, STRING, BOOL, STRING, STRING at [2:18].
Any thoughts?
Remove name from CASE name and replace double quotes " with single quotes ':
UPDATE table
SET name = CASE
WHEN name like '%aa%' then 'A'
WHEN name like '%er%' then 'E'
ELSE 'Z'
END
WHERE name is not null
P.S. in this example and your question query the word table is the name of the table not the keyword table. That means that in some databases you will have problems and you will have to put this word in quotes.
In this DEMO you can see that the query from my answer will work in MySQL database when you put word table in quotes.
In this DEMO you can see that the query from my answer will work in Oracle database when you put word table in double quotes. Also you will see that the strings(values of columns) can not be between double quotes in Oracle.
Note: Some of the databases will not cause errors if the string(column value) is between double quotes but it is better to use single quotes for this and because you have not tagged a database that you use this are some guidelines that will help you.
Remove the first name in the CASE clause:
UPDATE table
SET name = CASE WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
Exactly what The Impaler said,remove the first name in the CASE clause. SQL syntax does not call for the column name directly after case. For example (From W3 schools):
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;
https://www.w3schools.com/sql/sql_case.asp
Good luck!
Remove the first instance of the word name
UPDATE table
SET name = CASE
WHEN name like "%aa%" then "A"
WHEN name like "%er%" then "E"
ELSE "Z"
END
WHERE name is not null
There are two ways to use case:
1) CASE WHEN name=1 THEN WHEN name=2 THEN...
2) CASE name WHEN 1 THEN WHEN 2 THEN...
In the first case it looks for the first TRUE expression, in the second for the first expression that is equal to name.
You made a mix of the two, but for the interpreter it is the second form.
Therefore, it was looking for the first expression equal to name. When it reads the first WHEN, it checks whether name is equal to the argument (name like "%aa%")
But (name like "%aa%") is a boolean, name is a string, hence the error.
Related
I want to add a column called "Sweep" that contains bools based on whether the "Result" was a sweep or not. So I want the value in the "Sweep" column to be True if the "Result" is '4-0' or '0-4' and False if it isn't.
This is a part of the table:
I tried this:
ALTER TABLE "NBA_finals_1950-2018"
ADD "Sweep" BOOL;
UPDATE "NBA_finals_1950-2018"
SET "Sweep" = ("Result" = '4-0' OR "Result" = '0-4');
But for some reason, when I run this code...:
SELECT *
FROM "NBA_finals_1950-2018"
ORDER BY "Year";
...only one of the rows (last row) has the value True even though there are other rows where the result is a sweep ('4-0' or '0-4') as shown in the picture below.
I don't know why this is happening but I guess there is something wrong with the UPDATE...SET code. Please help.
Thanks in advance.
NOTE: I am using PostgreSQL 13
This would occur if the strings are not really what they look like -- this is often due to spaces at the beginning or end. Or perhaps to hyphens being different, or other look-alike characters.
You just need to find the right pattern. So so with a select. This returns no values:
select *
from "NBA_finals_1950-2018"
where "Result" in ('4-0', '0-4');
You can try:
where "Result" like '%0-4%' or
"Result" like '%4-0%'
But, this should do what you want:
where "Result" like '%4%' and
"Result" like '%0%'
because the numbers are all single digits.
You can incorporate this into the update statement.
Note: double quotes are a bad idea. I would recommend creating tables and columns without escaping the names.
I am moving a customer database which has a First Name, Last Name and Company Name. The current data will either have a First & Last Name or a Company name
In the new database I have a "Print Name" field which I need to combine the first and last name into, or if there is a company name present I need to use this value.
I have tried the bellow CASE WHEN expression to no avail.
SELECT
fstnam,
lstnam,
cmpnam,
CASE
WHEN csttbl.cmpnam = null THEN fstnam||' '||lstnam
ELSE csttbl.cmpnam
END as PrintName
FROM csttbl;
With the above query I only have a company name return in the print name column, not the combined First & Last Name. the returned data can be seen here https://drive.google.com/open?id=0B31ZRmFSX6rMYmNOczlRNE1lM2c
Any help would be appreciated
Change
csttbl.cmpnam = null
To
csttbl.cmpnam is null
RDBMS cannot compare null to any value, so using = with null is of no use. To compare nulls you should use is null which works on almost all RDBMS.
I would use coalesce():
SELECT fstnam, lstnam, cmpnam,
COALESCE(csttbl.cmpnam, fstnam|| ' ' || lstnam) as PrintName
FROM csttbl;
Didn't think of just concatonating the whole string as there is no First & Last name if there is a company name. COALESCE doesn't seem to work for me though so did the below
SELECT
fstnam,
lstnam,
cmpnam,
csttbl.cmpnam||fstnam|| ' ' ||lstnam as PrintName
FROM csttbl;
This should be a simple one, but I have not found any solution:
The normal way is using an alias like this:
CASE WHEN ac_code='T' THEN 'time' ELSE 'purchase' END as alias
When using alias in conjunction with UNION ALL this causes problem because the alias is not treated the same way as the other columns.
Using an alias to assign the value is not working. It is still treated as alias, though it has the column name.
CASE WHEN ac_code='T' THEN 'time' ELSE 'purchase' END as ac_subject
I want to assign a value to a column based on a condition.
CASE WHEN ac_code='T' THEN ac_subject ='time' ELSE ac_subject='purchase' END
Now I get the error message
UNION types character varying and boolean cannot be matched
How can I assign a value to a column in a case statement without using an alias in the column (shared by other columns in UNION)?
Here is the whole (simplified) query:
SELECT hr_id,
CASE WHEN hr_subject='' THEN code_name ELSE hr_subject END
FROM hr
LEFT JOIN code ON code_id=hr_code
WHERE hr_job='123'
UNION ALL
SELECT po_id,
CASE WHEN po_subject='' THEN code_name ELSE po_subject END
FROM po
LEFT JOIN code ON code_id=po_code
WHERE po_job='123'
UNION ALL
SELECT ac_id,
CASE WHEN ac_code='T' THEN ac_subject='time' ELSE ac_subject='purchase' END
FROM ac
WHERE ac_job='123'
There is no alias in your presented query. You are confusing terms. This would be a column alias:
CASE WHEN hr_subject='' THEN code_name ELSE hr_subject END AS ac_subject
In a UNION query, the number of columns, column names and data types in the returned set are determined by the first row. All appended rows have to match the row type. Column names in appended rows (including aliases) are just noise and ignored. Maybe useful for documentation, nothing else.
The = operator does not assign anything in a SELECT query. It's the equality operator that returns a boolean value. TRUE if both operands are equal, etc. This returns a boolean value: ac_subject='time' Hence your error message:
UNION types character varying and boolean cannot be matched
The only way to "assign" a value to a particular output column in this query is to include it at the right position in the SELECT list.
The information in the question is incomplete, but I suspect you are also confusing the empty string ('') with the NULL value. A distinction that you need to understand before doing anything else with relational databases. Maybe start here. In this case you would rather use COALESCE to provide a default for NULL values:
SELECT hr_id, COALESCE(hr_subject, code_name) AS ac_subject
FROM hr
LEFT JOIN code ON code_id=hr_code
WHERE hr_job = '123'
UNION ALL
SELECT po_id, COALESCE(po_subject, code_name)
FROM po
LEFT JOIN code ON code_id=po_code
WHERE po_job = '123'
UNION ALL
SELECT ac_id, CASE WHEN ac_code = 'T' THEN 'time'::varchar ELSE 'purchase' END
FROM ac
WHERE ac_job = '123'
Just an educated guess, assuming type varchar. You should have added table qualification to column names to clarify their origin. Or table definitions to clarify everything.
The CASE expression is supposed to return a value, e.g. 'time'.
Your value is another expression subject ='time' which is a boolean (true or false).
Is this on purpose? Does the other query you glue with UNION have a boolean in that place, too? Probably not, and this is what the DBMS complains about.
I found the problem.
CASE WHEN hr_subject=’’ THEN code_name ELSE hr_subject END
The columns code_name and hr_subject was different length. This caused the unpredictable result. I think that aliases can work now.
Thank you for your support.
I created a view for report. I imported data to the report. In columns null values are also present. If i filter one row using filter in vb.net the null values of row cannot be displayed.
For example, column names are ID, Name, Number, Place. In this some of the places number has null values I include filter ID, Name ,Number,Place. If I filter using ID the null values of number cannot be displayed.
This is the code I tried but not filter
IN FORM TextBox1.Text=""
TABLE1BindingSource.Filter = "YOUR FIELDNAME LIKE '" + TextBox1.Text.Equals (String.Empty) + "'")
Expected Result
Table
YOUR FIELDNAME
value1
value2
NULL
value3
NULL
NULL
value4
That filter doesn't make sense. This part:
TextBox1.Text.Equals(String.Empty)
is going to evaluate to Boolean, i.e. True if the TextBox is empty and False if it's not. That means that your filter ends up being:
YOUR FIELDNAME LIKE 'False'
or the like. What you should actually be doing is something like this:
Dim columnName As String
Dim fieldValue As String
'...
TABLE1BindingSource.Filter = String.Format("{0} LIKE '{1}%'", columnName, fieldValue)
Note a number of things there. Firstly, the use of String.Format to make this sort of code more readable. Secondly, the use of the actual value entered by the user and not a Boolean indicating whether that value was empty or not. Thirdly, the use of a wildcard because using LIKE without a wildcard makes no sense.
It should also be noted that that code is only going to work with text fields, because they are the only ones that get delimited by single quotes and the only ones that you can use LIKE with. If you want to filter on a numeric field or some other data type then you'll have to write your code to create the filter differently.
I would like to build one sql query in that one of my filed of form should not contain common names (maintained list of words in separate table) and i am passing value of that filed as parameter and want to check that it shouldn't contain any common name from that table.
How can i achieve that using sql query?
Note : if common name is 'abc' and i am passing parameter as '!abc123' since it contains that word query should return false.
Thanks in advance.
Try something like (Untested Query):
SELECT CommonName
FROM CommonNamesTable
WHERE CommonName like '%NameToTest%'
OR CONTAINS(NameToTest, CommonName);
Basically you need the string match options:
Take a look at options of CONTAINS and read about Queries with full text search
Is this what you're looking for?
SELECT (COUNT(*) == 0) FROM tablewithcommonwords
WHERE wordfromform LIKE CONCAT('%', wordcolumnnfromcommonwordstable, '%');
Try this:
IF NOT EXISTS(SELECT word FROM CommonWord WHERE #yourparam
LIKE '%' + word + '%')
BEGIN
RETURN 1
END
ELSE
BEGIN
Return 0
END
This works if the #yourParam is contained in any word or name, what you do not want to use. It only returns 1 if it is not contained by any row in the table.
I worte this sentence only on this way (you can use a simple Exists instead of NOT Exists), because may you want to extend the functionality in the true part.
if exists (select * from reservedwords where #parameter like '%'+word + '%')
select 0
else
select 1
I would like to suggest that You have to use keypress Event in Your TextBox and then Handle your Code after Each character enter in your TextBox.