The following code is working perfectly :
$aColumns = array( "t.tablename", "r.book_hours",
"GROUP_CONCAT(CASE WHEN r.reserveday = CURDATE() THEN r.formtime ELSE NULL END ORDER BY r.formtime ASC) AS oldBookTime");
But when I add multiple fields from this tutorial StackTutorial
I edit the code become :
$aColumns = array( "t.tablename", "r.book_hours",
"GROUP_CONCAT(CASE WHEN r.reserveday = CURDATE() THEN r.formtime, '-', r.book_hours ELSE NULL END ORDER BY r.formtime ASC) AS oldBookTime");
It shows error:
Query error: 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 ' '-'
Is it I have to escape , '-', ? How to escape it?
It isn't escaping that is the problem, is that the value following THEN must be a single scalar value, not a list of values.
Change this:
GROUP_CONCAT(CASE WHEN r.reserveday = CURDATE()
THEN r.formtime, '-', r.book_hours
ELSE NULL END ORDER BY r.formtime ASC) AS oldBookTime
To this:
GROUP_CONCAT(CASE WHEN r.reserveday = CURDATE()
THEN CONCAT(r.formtime, '-', r.book_hours)
ELSE NULL END ORDER BY r.formtime ASC) AS oldBookTime
(I inserted linebreaks for the sake of formatting this answer, but they're optional.)
In the CASE statement, you're using 3 results in the THEN branch. This is syntactically wrong. Here you can find the documentation for the CASE statement.
If I get what you want to achieve, you can use the CONCAT() function (documentation here) to concat your values, this way:
$aColumns = array( "t.tablename", "r.book_hours",
"GROUP_CONCAT(CASE WHEN r.reserveday = CURDATE() THEN CONCAT(r.formtime, '-', r.book_hours) ELSE NULL END ORDER BY r.formtime ASC) AS oldBookTime");
Related
I just built this new conditional query for pulling either a first_name AND last_name OR company_name based on the display_as value:
Select If(`display_as` = 'individual',
CONCAT(first_name, ' ', last_name)
,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1
The problem is, if the user has a first_name value only and no value for last_name, nothing is returned at all.
How can I fix this?
use this query instead.
$sql = "Select If(`display_as` = 'individual',
CONCAT(IFNULL(first_name, ''), ' ', IFNULL(last_name, ''))
,`company_name`) as name FROM `{$this->table}` WHERE `unique_id` = ? LIMIT 1";
try this one:
Select
If( `display_as` = 'individual',
CONCAT(coalesce(first_name, ''), ' ', coalesce(last_name, ''))
,`company_name`) as name
FROM `{$this->table}`
WHERE `unique_id` = ?
LIMIT 1
I would recommend writing this as:
select (case when display_as = 'individual'
then concat_ws(' ', first_name, last_name)
else company_name
end) as name
from `{$this->table}`
where unique_id = ?
limit 1; -- probably not needed
Notes:
case is the standard SQL construct for conditional logic. if() is a bespoke MySQL extension.
concat_ws() elegantly handles NULL values in the names. It simply ignores the the value rather than returning NULL.
Backticks are not required everywhere. They just make the query harder to write and read.
If your unique_id is really unique, you don't need LIMIT 1.
I have a MySQL update statement which is attempting to reset two columns: label and PersTrCode. (This is in a Coldfusion program.) I'm doing this with CASE statements but I can't seem to get the syntax right -- I keep getting an error. The code:
<cfquery name = 'nonull' datasource = "Moxart">
update FinAggDb
set Label = CASE
WHEN PersActIncOutg = 'I' && PersTrCode IS NULL THEN 'Total Income'
WHEN PersActIncOutg = 'O' && PersTrCode IS NULL THEN 'Total Expense'
WHEN PersActIncOutg IS NULL && PersTrCode IS NULL THEN ' '
ELSE PersTrCode
END
SET PersTrCode = CASE
WHEN PersTrCode IS NULL THEN 'Total'
ELSE PersTrCode
END
</cfquery>
The error is the usual informative statement:
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 'SET PersTrCode = CASE WHEN PersTrCode IS NULL THEN 'Total' ELSE PersTrCode ' at line 8
Are multiple CASE statements not allowed? Or can someone tell me how to fix this?
An update statement has only one set clause, with the various columns you want to update separated by commas. Also, note that it's more common to use and and not &&, although both are valid in MySQL:
update FinAggDb
set Label = CASE
WHEN PersActIncOutg = 'I' AND PersTrCode IS NULL THEN 'Total Income'
WHEN PersActIncOutg = 'O' AND PersTrCode IS NULL THEN 'Total Expense'
WHEN PersActIncOutg IS NULL AND PersTrCode IS NULL THEN ' '
ELSE PersTrCode
END
, -- comma here, not a second "set" clause
PersTrCode = CASE
WHEN PersTrCode IS NULL THEN 'Total'
ELSE PersTrCode
END
I have a sybase query that is structured like this:
SELECT
case
when isnull(a,'') <> '' then a
else convert(varchar(20), b)
end
FROM table_name
WHERE b=123
It used to return the results of the 'case' in a column named 'converted'. It now returns the results of the 'case' in a column with an empty string name ''.
How could this be? Could there be some database configuration that defaults the results of a 'case' with no name?
(I've fixed the broken query by adding " as computed" after 'end' but now I'd like to know how it used to return as 'computed' before I added the fix?)
Is this what you want?
SELECT (case when isnull(a, '') <> '' then a
else convert(varchar(20), b)
end) as converted
-------------^
FROM table_name
WHERE b = 123;
By the way, you could write the select more succinctly as:
SELECT coalesce(nullif(a, ''), b) as converted
I have a query that I am trying to convert to MySQL from MS SQL Server 2008. It runs fine on MSSQL,
I get the error
"Incorrect parameter count in the call to native function 'ISNULL'".
How do I solve this?
SELECT DISTINCT
dbo.`#EIM_PROCESS_DATA`.U_Tax_year,
dbo.`#EIM_PROCESS_DATA`.U_Employee_ID,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS033' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS PAYE,
CASE
WHEN dbo.`#EIM_PROCESS_DATA`.U_PD_code = 'SYS014' THEN SUM(dbo.`#EIM_PROCESS_DATA`.U_Amount)
END AS TOTALTAXABLE,
dbo.OADM.CompnyName,
dbo.OADM.CompnyAddr,
dbo.OADM.TaxIdNum,
dbo.OHEM.lastName + ', ' + ISNULL(dbo.OHEM.middleName, '') + '' + ISNULL(dbo.OHEM.firstName, '') AS EmployeeName
FROM
dbo.`#EIM_PROCESS_DATA`
INNER JOIN
dbo.OHEM ON dbo.`#EIM_PROCESS_DATA`.U_Employee_ID = dbo.OHEM.empID
CROSS JOIN
dbo.OADM
GROUP BY dbo.`#EIM_PROCESS_DATA`.U_Tax_year , dbo.`#EIM_PROCESS_DATA`.U_Employee_ID , dbo.OADM.CompnyName , dbo.OADM.CompnyAddr , dbo.OADM.TaxIdNum , dbo.OHEM.lastName , dbo.OHEM.firstName , dbo.OHEM.middleName , dbo.`#EIM_PROCESS_DATA`.U_PD_code
MySQL
SELECT DISTINCT
processdata.taxYear, processdata.empID,
CASE WHEN processdata.edCode = 'SYS033' THEN SUM (processdata.amount) END AS PAYE,
CASE WHEN processdata.edCode = 'SYS014' THEN SUM (processdata.amount) END AS TOTALTAXABLE,
company.companyName, company.streetAddress, company.companyPIN, employeemaster.lastName + ', ' + IFNULL(employeemaster.middleName, '')
+ ' ' + IFNULL(employeemaster.firstName, '') AS EmployeeName
FROM
processdata INNER JOIN
employeemaster ON processdata.empID = employeemaster.empID
CROSS JOIN company
GROUP BY processdata.taxYear, processdata.empID, company.companyName, company.streetAddress, company.companyPIN,
employeemaster.lastName, employeemaster.firstName, employeemaster.middleName, processdata.edCode
The MySQL equivalent of ISNULL is IFNULL
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns
expr2.
Maybe also look at SQL NULL Functions
The ISNULL from MySQL is used to check if a value is null
If expr is NULL, ISNULL() returns 1, otherwise it returns 0.
I would suggest that you switch to the ANSI standard function coalesce():
(dbo.OHEM.lastName + ', ' + coalesce(dbo.OHEM.middleName, '') + '' + coalesce(dbo.OHEM.firstName, '')
) AS EmployeeName
You could also make your query easier to read by including table aliases.
EDIT:
As a note, I seemed to have missed the direction of conversion. The MySQL query would use concat():
CONCAT(OHEM.lastName, ', ', coalesce(OHEM.middleName, ''),
coalesce(concat(' ', OHEM.firstName), '')
) AS EmployeeName
I was getting an error when running JUnit tests against a query which had ISNULL(value) with the error saying ISNULL needed two parameters. I fixed this by changing the query to have value is null and the code works the same while the tests now work.
I am trying to convert a string to a number. I have values stored like $4,215.35 so I want to convert that to a number so I can check if the value is greater than 50 or not.
If the value is greater than 50 then I want to update a field called first_sale_on with a time stamp.
Here is what I have done
UPDATE
account AS m
INNER JOIN ps_weekly_activations AS t ON t.mid = m.mid
SET
m.first_sale_on = CAST(CONCAT(STR_TO_DATE(t.Date_First_PL_Sale, '%c/%e/%Y'), ' 00:00:00') AS datetime)
WHERE
t.Date_First_PL_Sale IS NOT NULL
AND CONVERT(REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', ''), DECIMAL(18,2) ) >= 50;
I get the following error:
"Error code 1366: Incorrect decimal value '' at row -1..
The error means that I am trying to do operation on a string in the where statement. but I am not sure why the conversion is failing here. If the convert works then the query should execute with no problems.
I found the problem and the solution. The problem is that there was a bad data in that table that was throwing the query off.
To solve it I have added a check print i do the arithmetic. the check will check if the value is a number or not
This my new query (I hope my answer helps someone else)
UPDATE
account AS m
INNER JOIN ps_weekly_activations AS t ON t.mid = m.mid
SET
m.first_sale_on = CAST(CONCAT(STR_TO_DATE(t.Date_First_PL_Sale, '%c/%e/%Y'), ' 00:00:00') AS datetime)
WHERE
t.Date_First_PL_Sale IS NOT NULL
AND CONCAT('', REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', '') *1 ) = REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', '')
AND CONVERT(REPLACE(REPLACE(Private_Label_Net_Sales, '$',''), ',', ''), DECIMAL(18,2) ) >= 50;