Trying to dynamically change a value in sql - mysql

I am trying to generate a select statement with the hardcoded field in one column but with different values. Is there a better way to do this instead of writing another select statetment since there are different hardcoded values?
select
ppp.category_id,
ppp.city_id,
<<hardcoded values>>,
ppp.address,
ppp.status
from product ppp
where ppp.owner_id = 4186

Expressions in the select-list must be fixed at the time the query is prepared. You can't change that dynamically after the query has been parsed.
If your expression is a constant value, you can inject it as a parameter. Then you can pass the parameter to a prepared statement as you execute the query.
select
ppp.category_id,
ppp.city_id,
? as the_third_column,
ppp.address,
ppp.status
from product ppp
where ppp.owner_id = 4186
If you have a fixed list of expressions, you could use a CASE statement, and this means it can vary by row, or else by a query parameter:
select
ppp.category_id,
ppp.city_id,
CASE ppp.fetch_style
WHEN 1 THEN LOWER(ppp.mycolumn)
WHEN 2 THEN UPPER(ppp.mycolumn)
WHEN 3 THEN REVERSE(ppp.mycolumn)
ELSE ppp.mycolumn
END AS mycolumn,
ppp.address,
ppp.status
from product ppp
where ppp.owner_id = 4186

Related

Possible to use IF in a query?

I'm using Grafana to plot data from a MySQL datasource. Is it possible to, in a panel's query editor, use an IF ... THEN ... type statement. I would like to create a variable that I could put in the IF. I want the variable to be a condition, not necessarily to be used directly in the query.
For example:
//IN THE DATA SOURCE:
CREATE TABLE Example (Id INT, ANIMALS VARCHAR(15));
INSERT INTO Example VALUES (1,'Dog'), (2,'Fish'), (3,'Cat'), (4,'Lizard')
For a variable Test with values "Mammal',"Reptile", "Other":
//WHAT I'D LIKE IN GRAFANA QUERY EDITOR:
IF($Test = "Mammal") THEN
SELECT * FROM Example WHERE Id = 1 OR Id =3;
ELSE
SELECT * FROM Example WHERE Id = 2 OR Id =4;
END IF;
Is this kind of condition based query even possible? If so, what is the proper syntax to get it to work? Is there any way I can use Grafana variables to have a similar effect?
Use query. Query starts with SELECT keyword. Don't use any IF ELSE conditions before query, e.g.:
SELECT *
FROM Example
WHERE
Data IN ( ${variable:csv} )
This WHERE condition syntax will work with single value, multi value Grafana dashboard variables and also with All value (no custom All value, but blank=auto). Of course this condition is mainly for INT column types. STRING types may need different one (e.g. with LIKE and regexp matching).
Code all your logic (dependency on the dashboard variable) in the WHERE section. Use query inspector to see SQL which is generated and tweak it to correct SQL syntax.
Instead of an if, you can use or. It's really useful for conditionally checking variables:
select * from Example
where (Id in (1,3) or '$Test' != 'Mammal')
and (Id in (2,4) or '$Test' == 'Mammal')

IIF When Using Similar Criteria

Their are 2 different jobstatuses that I want to display the same way, my IIF statement changes the display, BUT I would like for only one entry to be returned for both. For example, I want it to show like this
JobStatus
---------
Inactive
Let Go
But the returned result set I get is
JobStatus
---------
Active
Inactive
Let Go
Let Go
What do I need to change in my query to make it show like I need? (and I need this to be done via a query not vba)
jobstatus1: IIf([jobstatus]="Terminated","Let Go",IIf([jobstatus]="Fired","Let Go",[jobstatus]))
EDIT -- Full Syntax. The IIF statement I need to use is for the alpha.jobstatus line right after the Select
SELECT alpha.jobstatus, Count(beta.ID) AS CountOfID
FROM alpha LEFT JOIN beta ON alpha.jobstatus = beta.jobstatus
GROUP BY alpha.jobstatus, alpha.order
HAVING (((alpha.jobstatus) Not In (Select [jobstatus] From tbl_Valid)))
ORDER BY alpha.order;
Use SELECT DISTINCT to return only distinct values.
Also you can use a simpler expression for that calculated field --- one with a single IIf instead of nested IIf's. Switch your query to SQL View and revise the start of the statement text to this ...
SELECT DISTINCT IIf([jobstatus] IN ('Terminated', 'Fired'), 'Let Go', [jobstatus]) AS jobstatus1

SSRS Parameter values in WHERE clause

(edited to clean up)
I have an SSRS report with a multi-value parameter. What I need is for each value of the parameter to correspond to a condition in the "where" clause.
So my query is like this:
select stuff,...
WHERE
column A != column B OR
column C != column D OR...
just like that all the way down. It's to give results only if there's a difference between different pairs of columns.
So hope I'm describing it well. So, for example, if the above is my where clause, I want the parameter to have values like this:
"Difference between A & B"
"Difference between C & D"
and be able to select multiple...so only the ones the user selects are incorporated.
EDIT - PARTIAL SOLUTION **********************************************
Ok I have the logic, thanks to the right direction from Hannover Fist, I came up with this:
WHERE
col 1 <> CASE WHEN CHARINDEX("Where1",#Parameter) = 0 THEN col 1 ELSE col 2 END OR
col 3 <> CASE WHEN CHARINDEX("Where2",#Parameter) = 0 THEN col 3 ELSE col 4 END
...etc.....
This way, if the parameter is not selected, that part of the where clause looks for results where that column is not equal to itself--so none, of course...
However, one problem remains. This works in SSRS if I only choose 1 of the parameter values, but if I choose more than one, I get an error "charindex function requires 2 to 3 arguments." >-(
I deployed it and it spat something slightly different:
Argument data type nvarchar is invalid for argument 3 of charindex function
Something about SSRS's handling of this is flapdoodle, but I'm not sure what.
I'm a little fuzzy as to how you're trying to do this.
How about having your WHERE clause in your SQL and use your parameter to determine whether that part of the WHERE is used? This may not be exactly what you need but should give you an idea of what I mean.
WHERE (ColA <> ColB or CHARINDEX("Where1", #Parameter) = 0)
Your Parameter would have Where1 as one of the selections (for the Value - the Label could be more descriptive). If it's chosen, the CHARINDEX result would not be 0 and the ColA <> ColB condition would need to be true to show that record.
Repeat for each parameter/WHERE combo you need.
Got it.
As edited above, this code works (helpful nudge in this direction from Hannover Fist):
WHERE
col 1 <> CASE WHEN CHARINDEX("Where1",#Parameter) = 0 THEN col 1 ELSE col 2 END OR
col 3 <> CASE WHEN CHARINDEX("Where2",#Paremeter) = 0 THEN col 3 ELSE col 4 END
etc...
And the parameter issue is new to my experience, but put simply (which is not done often--hence my difficulty :-P), SSRS includes the commas between parameter values (which makes sense since we can use an IN statement such as
WHERE column IN (#Parameter)
So that is why it complained when I selected more than one. Incorporating the excellent selected answer here:
Passing multiple values for a single parameter in Reporting Services
Solved the rest of the problem :)
When you are passing the multivalue parameter to dataset
join the multivalue parameter with expression
= JOIN(Parameters!multivalue parameter.Value,",")

SSRS - Limiting results using multiple parameters

I'm creating a debtor invoicing report which has two parameters.
Parameter 1: This is a single value parameter called #booking_date. I filter the results(main dataset) by adding this into the query as a query parameter.
Eg. WHERE BookingDate = #booking_Date
Parameter 2: This parameter has two specified values - Yes or No. The parameter is called #live_run and the default value is 'No'. Basically, when this parameter has the default value of 'No', it does not limit/effect the results in any way. On the other hand, when this parameter has a value of 'Yes', it should limit the results by only displaying the bookings where the invoice has been paid off. There is a field I can use for this called Booking_Paid_off as follows - WHERE Booking_Paid_Off = 1.
I have parameter 1 in place, but I am unsure how to bring in Parameter 2 because it will be based on two conditions, do I need to use an If statement or a case statement? Do I need to create a new dataset for the second Parameter? I only want to limit the results with Parameter 2 ONLY if Parameter 2 has a value of Yes, otherwise I want the results to stay the same.
You have many options. You can switch out the Dataset entirely based on the parameter or use an IF inside the dataset to determine which query to run or simply check the parameter in your WHERE clause.
I recommend the latter.
SELECT
Field1,
Field2
FROM
Table1
WHERE
(
(#live_run = 'Yes' and Booking_Paid_Off = 1)
or (#live_run <> 'Yes')
)

Running a SQL SELECT statement against a MYSQL column of SET type

I'm trying to run a SQL SELECT statement against a column that is of type SET. The table is called myTable and the columns in myTable are called base_props and names. The base_props column is of type SET. The values in base_prop are vb,nt, cnt,poss and loc. So I would like to SELECT entries from the column 'name' where base_props have both the values, vb and poss. The results I'm looking to get may have values other than just vb and poss. So to be clear I would like to select all entries that have the values vb and poss regardless if they have other values as well. I've tried the following SQL queries but I can't get the desired results.
SELECT name from myTable WHERE base_props = 'vb' AND base_props = 'poss'
That query returns an empty result set. I've tried using FIND_IN_SET() and IN() but I couldn't get anywhere with that. I've written SQL statements before but never had to deal with columns that are type SET. Any help is appreciated.
The only thing I can come up with is using the LIKE keyword:
SELECT name FROM myTable WHERE (base_props LIKE '%vb%' AND base_props LIKE '%poss%');
This will make sure both vb and cnt are in the base_props column. Of course you can use cnt, nt and loc in there, or any number of base_props values in the sql, just add more AND statements.
OR as a deleted answer by samitha pointed out, you can use FIND_IN_SET:
SELECT name from myTable WHERE FIND_IN_SET('vb', base_props) AND FIND_IN_SET('poss', base_props);
Comment (by spencer7593): "both of these work, but there is a slight difference. The LIKE operator will actually match any member that includes the search string anywhere in a term; the FIND_IN_SET function will only match an exact member. It's also possible to search for members in set by the order they appear in the SET definition, using the MySQL BITAND operator: for example, to match the 1st and 4th members of the set: WHERE base_props & 1 AND base_props & 8". So for example, if you have 'a' and 'aaa' in your set, then using the LIKE "%a%" method will also return rows containing 'aaa'.
Conclusion: use the FIND_IN_SET solution since it will work for all cases.
FIND_IN_SET return index, Try this
SELECT name from myTable WHERE FIND_IN_SET(base_props, 'vb') > 0 AND
FIND_IN_SET(base_props, 'poss') > 0