Concat in If statement - mysql

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

Related

Ignore text and extract number betwen 8 and 12 digits long

I wish to extract only a number if it's between 8 and 12 digits long, otherwise I wish it to be a blank. However in the column of data there can be text which I want as a blank.
Have tried may alterations of the code below with different brackets, though I get an error
SELECT CASE WHEN
isnumeric(dbo.worksheet_pvt.MPRNExpected) = 0 THEN '' ELSE(
CASE WHEN(
len(dbo.worksheet_pvt.MPRNExpected) >= 8
AND len(dbo.worksheet_pvt.MPRNExpected) < 13
) THEN dbo.worksheet_pvt.MPRNExpected ELSE ''
END
) AS [ MPRN Expected ]
Assuming you are using SQL Server, I would suggest:
select (case when p.MPRNExpected not like '%[^0-9]%' and
len(p.MPRNExpected) between 8 and 12
then p.MPRNExpected
end) as MPRN_Expected
. . .
from dbo.worksheet_pvt p
Presumably, you don't want isnumeric(), because it allows characters such as '.', '-', and 'e' in the "number".
The problem with your code is that you have two case expressions and they are not terminated correctly.
As a note, in MySQL, you would use regular expressions:
select (case when p.MPRNExpected regexp '^[0-9]{8-12}$'
then p.MPRNExpected
end) as MPRN_Expected
. . .
from dbo.worksheet_pvt p
Try this query
SELECT CASE WHEN ISNUMERIC(COLUMN_NAME)=0 THEN '' ELSE
CASE WHEN (LEN(COLUMN_NAME)>=8 AND LEN(COLUMN_NAME)<13)
THEN COLUMN_NAME ELSE ''END END AS data FROM TABLE_NAME
Thanks.

IF condition doesn't work properly

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.

Using CASE in WHERE Statement when parameter has multiple values

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)))

Cannot set the command text for dataset error in SSRS 2008 R2 while getting data from MYSQL

I have searched through all the posts I could find regarding the "Cannot set the command text for dataset" error I am getting, and everything that users suggest, still results in this error for me.
I am working in SSRS 2008R2, and I am connecting via ODBC to a MYSQL connection.
="SELECT case when tranHour between '00' and '03'
then DATE_format(DATE_SUB(trandate,INTERVAL 1 DAY), '%Y-%m-%d')
else DATE_format(trandate, '%Y-%m-%d')
end as WorkDay,
case when tranHour between '03' and '15' then 'AM'
else 'PM'
end as Shift,
'Station1' AS Station,
count(*) as 'Scans',
ROUND(SUM(elapsed_seconds)/60/60,2) as 'Hours',
ROUND(count(*)/(SUM(elapsed_seconds)/60/60),2) as 'Scans/Hour',
season
FROM data_lite.master_lite_134_301
where SEASON IN ('" + join(Parameters!ReportParameter1.Value,"','") + "')
group by WorkDay, Shift
ORDER BY DATE_format(WorkDay, '%Y-%m-%d') DESC"
Every time I get this error...
An error occurred during local report processing.
Cannot set the command text for dataset 'AMPM'
Error during processing of the CommandText expression of dataset 'AMPM'
If I replace the Parameter with an actual value, it runs fine.
So with where SEASON = '15F' , it runs,
with where SEASON IN ('" + join(Parameters!ReportParameter1.Value,"','") + "') , it gets this error
I had the similar issue. I had everything correct my tables, fields and query as well. What resolved my issue was checking "multiple values" box in parameters.
Go to your parameters --> double click on it --> If you have default value set it in default value tab --> In general tab check multiple values option.
Build your report again/ delete the .rdl.data file from the folder and then check your report it should work perfectly fine.
change your CASE to
SELECT case when ( tranHour between '03' and '15') then 'AM'
else 'PM'
end CASE as Shift;
so
="SELECT case when tranHour between '00' and '03'
then DATE_format(DATE_SUB(trandate,INTERVAL 1 DAY), '%Y-%m-%d')
else DATE_format(trandate, '%Y-%m-%d')
end as WorkDay,
case when ( tranHour between '03' and '15') then 'AM'
else 'PM'
end CASE as Shift,
'Station1' AS Station,
count(*) as 'Scans',
ROUND(SUM(elapsed_seconds)/60/60,2) as 'Hours',
ROUND(count(*)/(SUM(elapsed_seconds)/60/60),2) as 'Scans/Hour',
season
FROM data_lite.master_lite_134_301
where SEASON IN ('" + join(Parameters!ReportParameter1.Value,"','") + "')
group by WorkDay, Shift
ORDER BY DATE_format(WorkDay, '%Y-%m-%d') DESC"
You have to map the Query parameter with the corresponding Report parameter.
In Dataset properties go to Parameters tab, map the name of the query parameter with name of the report parameter.
Now in your query you can use the parameter in this way - only if it is a multivalue parameter.
SELECT case when tranHour between '00' and '03'
then DATE_format(DATE_SUB(trandate,INTERVAL 1 DAY), '%Y-%m-%d')
else DATE_format(trandate, '%Y-%m-%d')
end as WorkDay,
case when tranHour between '03' and '15' then 'AM'
else 'PM'
end as Shift,
'Station1' AS Station,
count(*) as 'Scans',
ROUND(SUM(elapsed_seconds)/60/60,2) as 'Hours',
ROUND(count(*)/(SUM(elapsed_seconds)/60/60),2) as 'Scans/Hour',
season
FROM data_lite.master_lite_134_301
where SEASON IN (#QueryYearParameter)
group by WorkDay, Shift
ORDER BY DATE_format(WorkDay, '%Y-%m-%d') DESC
Note Parameter Name property and the parameter I use in the query is
the same.
Let me know if this helps you.
SSRS is funny about its spaces at the end of lines in the expressions. I had the same issue and SSRS was combining the last word of the line with the first word of the next line. Just add a space in at the end of every line.
OR
Wrap your JOIN func in CSTR(). so... CSTR(join(Parameters!ReportParameter1.Value,"','"))

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.