IF condition doesn't work properly - mysql

I would like to write a query using IF, but its not working , what's wrong with this query?
SELECT
IF(Emp.Name is not null)
((Emp.Name) + '_' + (Emp.LastName)) as ID
else
Emp.ID
I get this error:
Incorrect syntax near the keyword 'IF'.
Why is that?
Thank you.

You can use CASE EXPRESSION :
SELECT CASE WHEN emp.name is not null THEN emp.name + '_' + emp.lastName
ELSE Emp.id
END as [ID]
FROM ...
The IF() is performed differently in SQL-Server (I assume by the concat syntax),
IF ( Condition )
SQL STATEMENT
ELSE
SQL STATEMENT
Which means you need to perform the entire select in each block. Your kind of IF() is used in MySQL , IF(Condition , THEN , ELSE )

Try using Case in your query check this MySQL: CASE Function

You need to do this in a CASE clause:
SELECT
CASE WHEN (Emp.Name IS NOT NULL)
THEN ((Emp.Name) + '_' + (Emp.LastName))
ELSE
Emp.ID
END as ID
The IF..ELSE syntax is somewhat different:
IF(Emp.Name IS NOT NULL)
SELECT ((Emp.Name) + '_' + (Emp.LastName)) AS ID
ELSE
SELECT Emp.ID AS ID

Assuming it's SQL Server based on your syntax use this:
SELECT CASE <variable> WHEN <value> THEN <returnvalue>
WHEN <othervalue> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname>
FROM <table>

Instead of usinf IF, you can use CASE in SELECT statement. Something like this
SELECT
CASE Emp.Name
WHEN NULL THEN Emp.ID
ELSE CONCAT(CONCAT(Emp.Name,'_'),Emp.LastName)
END AS "ID"
FROM Emp;
Hope it helps.

Related

How can I concat columns as null-safe?

Here is my code:
SELECT COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'unknown') name
FROM users u
WHERE id = 10;
The result will be unknown when either user_fname or user_lname is null. That's not what I want, I want to select unknown only when both user_fname and user_lname are null.
Otherwise, I want to get the value of not-null column. How can I do that?
Use concat_ws():
SELECT CONCAT_WS(' ', u.user_fname, u.user_lname) name
FROM users u
WHERE id = 10;
This has the nice benefit that if either of the names are null, you don't get a spurious space in the result.
It gets a little tricky if you want to convert NULLs to "unknown". This should do the trick:
SELECT COALESCE(NULLIF(CONCAT_WS(' ', u.user_fname, u.user_lname) , ''), 'unknown') as name
FROM users u
WHERE id = 10;
You could use:
SELECT COALESCE(
TRIM(CONCAT(COALESCE(u.user_fname,''), ' ', COALESCE(u.user_lname,''))),
'unknown') name
FROM users u
WHERE id = 10;
I always like the isnull function in sql server (or nvl in oracle):
SELECT isnull(u.user_fname + ' ','') + isnull(u.user_lname, '') name
FROM users u
WHERE id=10
but then to switch include the Nulls, I would use a case:
SELECT
CASE WHEN u.user_fname IS NULL AND u.user_lname is NULL THEN 'unknown'
ELSE isnull(u.user_fname + ' ','') + isnull(u.user_lname, '') END name
FROM users u
WHERE id=10
yes, it's a little longer than the other answers, but easier to read and perhaps more flexible in the future in case you have other conditions.
Not really a performance hit either way, so it's down to personal preference.

Can Sybase CASE expressions have a default column name for their result?

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

How to Concat data using COALESCE in MySql

This is my SQL query
DECLARE #strManualRefundIdList AS VARCHAR(MAX)
SELECT #strManualRefundIdList = COALESCE(#strManualRefundIdList + '|', '') + CONVERT(VARCHAR(MAX), ManualRefund_strReasonCode)
FROM tblManualRefunds WHERE ManualRefund_lngId IN ( 20 ,21 ,22 )
SELECT #strManualRefundIdList;
This gives like pivot, all the rows concatenated in a single row.
The Same i need to convert into MySql Query.
I tried like this
SELECT
CONCAT(COALESCE(CONCAT(v_strManualRefundIdList, '|'), '') , ( ManualRefund_lngId))
INTO
v_strManualRefundIdList
FROM tblManualRefunds
WHERE Trans_lngId IN ( 20 ,21 ,22 ) ;
But it throws error as Error Code: 1172. Result consisted of more than one row
How to translate that query. I am new to database.
Please help me in figuring out this.
UPDATE :
The way i found out was assigning into a cursor and loop through and concatenate it.
But is that the only way ? or any better way is available ?
SELECT group_concat(ManualRefund_strReasonCode SEPARATOR '|')
FROM tblManualRefunds
WHERE manualRefund_lngId in (20,21,22)
SQL Fiddle
As per xQbert Comment i tried this
SELECT
GROUP_CONCAT(COALESCE(CONCAT('shan', '|'), '') , ( ManualRefund_lngId))
INTO
#v_strManualRefundIdList
FROM tblManualRefunds ;
Its working fine.
Thanks Man.. !!!

SQL Server case when charindex

I am trying to get this case when statement to work in SQL Server 2008 R2. It keeps saying the '>' symbol is invalid in the case when statement for the CHARINDEX part.
select
count(r.id) as request,
case r.servicelayer
when null then r.topic + '/IAL'
when '' then r.topic + '/IAL'
when CHARINDEX('/rssfeed1234/georss/SomMobile', i.URI_STEM) ***>*** 0 then 'Som Mobile'
else r.topic + '/' + r.servicelayer
end as [layername]
from iis_metrics.tblReportData as r
Well, you're mixing two different ways of using CASE in an invalid way.
Either you use CASE (some column name) and then you must use just some condition that applies to that column. This is OK in the first two clauses: WHEN NULL or WHEN '' (this is sort of a "short hand" for using WHEN .. IS NULL or WHEN ... = '' - but if you start using this "short hand" notation, you need to use it in all your WHEN clauses)
But in this case, you cannot suddenly have a complete expression in your WHEN.... clause as you're trying in your third clause.
This is the OR version: you can also use just CASE and then each WHEN clause has a complete expression - try this:
CASE
WHEN r.servicelayer IS NULL THEN r.topic + '/IAL'
WHEN r.servicelayer = '' THEN r.topic + '/IAL'
WHEN CHARINDEX('/rssfeed1234/georss/SomMobile', i.URI_STEM) > 0 THEN 'Som Mobile'
ELSE r.topic + '/' + r.servicelayer
END AS [layername]
This should now work - each of your WHEN clauses contains a complete expression and thus this CASE statement is valid.

Incorrect parameter count in the call to native function 'ISNULL'

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.