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.
Related
I am trying to join two if statements together in an SQL query, but I don't seem to be having much luck.
The two statements are:
if(c.population > 100000000, Concat("Large ", c.GovernmentForm), c.GovernmentForm)
and:
if(YEAR(now())-c.IndepYear > 50, Concat("Modern ", c.GovernmentForm, c.GovernmentForm)
Both of these IF statements work separately of each other, but I need them to be combined into one (e.g. the output to be "Modern Large" & GovernmentForm, in a separate column on the output). I could do it as a function, or procedure, but they seem to be blocked on the MySQL we are using.
Any suggestions?
Put the conditional logic inside the concat() function:
concat( (case when c.population > 100000000 then 'Large ' else '' end),
(case when YEAR(now()) - c.IndepYear > 50 then 'Modern ' else '' end),
c.GovernmentForm
)
This will put both, one, or neither of the prefixes depending on the conditions.
You could use a case when .. end
case when c.population > 100000000 AND YEAR(now())-c.IndepYear > 50
then Concat("Large Modern ", c.GovernmentForm), c.GovernmentForm)
end ,
case when c.population > 100000000
then Concat("Large ", c.GovernmentForm), c.GovernmentForm),
End
case when YEAR(now())-c.IndepYear > 50
then Concat("Modern ", c.GovernmentForm, c.GovernmentForm)
End
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.
I have a problem which I think relates to having a multiple value parameter.
In my TblActivity there are two fields TblActivity.ActivityServActId and TblActivity.ActivityContractId which I want to include in my WHERE statement.
Filtering by these is optional. If the user selects 'Yes' for the parameter #YESNOActivity, then I want to filter the query looking for rows where TblActivity.ActivityServActId matches one of the options in the parameter #ServiceActivity.
The same goes for the #YESNOContract, TblActivity.ActivityContractId and #Contract respectively
I managed to get to this:
WHERE
(CASE WHEN #YESNOActivity = 'Yes' THEN TblActivity.ActivityServActId ELSE 0 END)
IN (CASE WHEN #YESNOActivity = 'Yes' THEN #ServiceActivity ELSE 0 END)
AND (CASE WHEN #YESNOContract = 'Yes' THEN TblActivity.ActivityContractId ELSE 0 END)
IN (CASE WHEN #YESNOContract = 'Yes' THEN #Contract ELSE 0 END)
However, although this code works fine if there is only one value selected in the parameter #ServiceActivity or #Contract, as soon as I have more than one value in these parameters, I get the error:
Incorrect syntax near ','.
Query execution failed for dataset 'Activity'. (rsErrorExecutingCommand)
An error has occurred during report processing. (rsProcessingAborted)
Can anyone see what I'm doing wrong? I could understand it if I had an = instead of IN in the WHERE statement but can't figure this one out.
Using SQL Server 2008 and SSRS 2008-r2
If your #ServiceActivity is something like 1,2,3
You can do something like this
WHERE `,1,2,3,` LIKE `%,1,%`
So you format your variables
WHERE ',' + #ServiceActivity + ',' LIKE '%,' + ID + ',%'
SQL FIDDLE DEMO
SELECT *
FROM
(SELECT '1,2,3,4' as X UNION ALL
SELECT '2,3,4,5' as X UNION ALL
SELECT '3,4,5,6' as X UNION ALL
SELECT '1,3,4,5' as X
) as T
WHERE ',' + X + ',' LIKE '%,1,%'
For Your Case
(CASE WHEN #YESNOActivity = 'Yes'
THEN ',' + #ServiceActivity + ','
ELSE NULL
END)
LIKE
(CASE WHEN #YESNOActivity = 'Yes'
THEN '%,' + TblActivity.ActivityServActId + ',%'
ELSE 0
END)
In SQL, the IN clause does not support parameters the way you are using them. The general syntax is
IN (1, 2, 3, 4)
you have
IN (#Param)
where something like
#Param = '1, 2, 3, 4'
Internally, SQL will turn this into
IN ('1, 2, 3, 4')
Note the quotes... you are now matching against a string!
There are a number of ways to address this. Search SO for "sql in clause parameter", pick one that works for you, and upvote it.
(Added)
Parameterize an SQL IN clause seems pretty definitive on the subject. While long ago I upvoted the third reply (the one with table-value parameters), any of the high-vote answers could do the trick. The ideal answer depends on the overall problem you are working with. (I am not familiar with SSRS, and can't give more specific advice.)
So after a lot of messing around I put together a simple workaround for this by dropping my use of CASE altogether - but I have a suspicion that this is not a terribly efficient way of doing things.
WHERE
(#YESNOActivity = 'No' OR (#YESNOActivity = 'Yes' AND
TblActivity.ActivityServActId IN (#ServiceActivity)))
AND
(#YESNOContract = 'No' OR (#YESNOContract = 'Yes' AND
TblActivity.ActivityContractId IN (#Contract)))
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.