Is it possible to use this sql query?
select ([discount_type]='Percent') ? [Percent]+'%' : [Amount]+'RS' as [Discount] from [admin].[discount] where [discount_id]=2
You can make a CASE (which is pretty much like a switch in many other languages)
SELECT
CASE [discount_type]
WHEN 'Percent' THEN [Percent] + '%'
ELSE [Amount] + 'RS' END as [Discount]
FROM [admin].[discount]
WHERE [discount_id] = 2
Note that the rest of the query uses your code as is, i.e. assuming that Percent can be concatenated with a string without prior conversion.
Related
I need help in mysql query, i written this query
select * from post where content REGEXP '^q'
this query is working but it also includes spaces in filter, what i want to do if any content string like "qqqqqq" or "qqqq" or "qqq" or "qq" or "q" for this string only it should have to filter, right now what is happening if i have string like "qqqq qq" then also it is giving me the result, it should not consider that space, can anyone please help me to resolve this issue ?
You can fix your regexp like next:
select * from post where content REGEXP '^q+$';
This regular expression mean the string starts with q and contain only 1 or more q symbols till end of string
Test it on SQLize.online
Try Using this ^q+(?![\s])+$ Regular Expression.
Above RegExp will check for string starting with q and without space.
You don't really need a regex for this. String functions are likely to be more efficient. You can replace all "q"s with empty strings, and ensure that that resulting string is empty:
select * from post where replace(content, 'q', '') = ''
Note that this also allows the empty string. If you want to avoid that, then:
select * from post where content <> '' and replace(content, 'q', '') = ''
I'm trying to get a row from the database but when using binding. I know that this doesn't work because the query automatically puts single quotes so it will be like this: select model, magazine, round('name', 2) etc. This doesn't work of course but how do I get rid of the single quotes?
$merkinformation = DB::select('select Model, Magazine, round(?, 2) as Rondetijd from rondetijden where Merk = ? order by ? limit 3;', [$track, $merk, $track]);
You can't use column nmaes like this.
You must concatinate the name of the column. But this is vulnerable to sql injection. So you must check if $track has a valid content
$merkinformation = DB::select('select Model, Magazine, round(`' . $track . '` , 2) as Rondetijd from rondetijden where Merk = ? order by ? limit 3;', [$merk, $track]);
there is ['] single quote and [`] punctuation mark. If start with single quote or double quote mysql will translate that as string where punctuation mark will be recognize as field name.
Are you sure that is a single quote ?
How do I use Codeigniter SQL Binding if there are two target dates?
Is how I did it below correct?
public function getInvestmentForBorrowing($id, $Interest, $Currency, $Loantime, $target_date, $Risk_category)
{
$query = '
select CASE WHEN (a.amount_financed - a.amount_invested - a.amount_withdrawn) < a.amount_per_borrower
THEN round((a.amount_financed - a.amount_invested - a.amount_withdrawn), 2)
ELSE round((a.amount_per_borrower) , 2)
END AS investable_amount, a.*,
c.IBAN as Return_IBAN, c.BIC as Return_BIC,
i.average_rate
from investment a
inner join userinfo c
on a.Owner = c.Owner and
c.UPDATE_DT is null
inner join exchange_rates i
on a.Currency = i.currency_id and
? between i.effective_dt and i.expiration_dt
where a.ORIG_ID = ? and
a.Interest <= ? and
a.Currency = ? and
a.status = 2 and
a.Loantime >= ? and
a.Available >= ? and
a.Risk <= ? and
a.UPDATE_DT is null
having investable_amount > 0';
$query = $this->db->query($query, array($target_date, $id ,$Interest, $Currency, $Loantime ,$target_date ,$Risk_category));
$result = $query->result();
return $result;
}
Write now the question marks just represent the array so I added two $target_date to the array but not sure if thats the right way to do it.
It appears to be ok according to the codeigniter documentation but i say that without regard to your original SQL being correct or not.
Just make sure that the number of ? match the number of values you are providing and they are in the right order.
One way to sanity check it, apart from just running it, is to place the following command right after you perform the query:
echo $this->db->last_query();
And providing it known data, you can cheat and just hard code some dummy values for testing, take the generated SQL and throw that into something like phpmyadmin and run it the generated SQL against the Database and see if it works with the expected results.
Just a side note regarding your variable naming style. I see you are mixing cases i.e. things like $target_date (all lower case) and $Risk_category (First letter uppercase). Just be aware that on a linux based system case does matter and mixing like that can cause errors. It's a good idea to decide on one and stick with it.
I'm working on my colleague's old project and I found on her code WHERE TRUE AND ID='1' AND STAT='1'.
I've tried to removed TRUE AND so the query become WHERE ID='1' AND STAT='1' and get the same result.
I know we can use TRUEas boolean to search 'where something is true' such as WHERE FLAG = TRUE and this MySQL documentation state that
The constants TRUE and FALSE evaluate to 1 and 0, respectively. The constant names can be written in any lettercase.
I also tried SELECT * FROM MYTABLE WHERE TRUE but it's just the same as SELECT * FROM MYTABLE
what is the purpose of TRUE in her query?
It has no specific functional purpose. Your colleague may have included it if they were adhering to a specific style guide that recommends that all SELECT queries have explicit WHERE clauses. If an explicit WHERE clause is not provided, the default is to select all rows. Adding a WHERE clause that is always true will have the same effect.
Another way this query could have come about is if it was generated by a code generation tool that always had to write in a WHERE clause due to the way it was written.
for example:
myQuery = "SELECT X FROM Y WHERE " + ConditionMet(data)?" AccountID = '" + AcctId + "'" : "1=1";
This means that if ConditionMet(data) is true, then only return rows where AccountID matches the AcctId you are passing in. If it is false, then return all rows.
Adding a "dummy" 1=1 makes the code generator simpler to write. More generally, 1=1 is as legitimate a boolean clause as any other, and can be "dropped" into a conditional expression without having to special-case the query to omit the WHERE clause.
Similarly, adding a WHERE clause that is always false (e.g. "WHERE 1=0") will result in zero rows being returned.
Do note that the example code here is vulnerable to SQL Injection, so it should not be used in cases where you are dealing with AccountID's that you did not produce yourself. There are multiple ways to secure it that are beyond the scope of this answer.
If you're writing your SQLString on runtime, and you might add different "where" clausules but you don't know which of all of them will be the first, it makes it easy as all of them may start with "AND ....."
Example:
SQLString:='SELECT * FROM YOUTABLE WHERE TRUE'
If condition1 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition2 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition3 THEN SQLString:=SQLString+' AND Whatever=whatever';
If condition4 THEN SQLString:=SQLString+' AND Whatever=whatever';
otherwhise, you should add the WHERE clause not on the first SQLString:= but on the first condition that happens to be true, which you don't know will it be a priori
it is not as much relevant but if find important where adding dynamic conditions,for example in php.
$condition_stmt="";
if ($start_date !="" && $end_date!="")
{
$condition_stmt="and nos.status_date between '".$start_date."' and '".$end_date."'";
}
else if ($start_date!="")
{
$condition_stmt="and nos.status_date >='".$start_date."'";
}
else
{
$condition_stmt="and nos.status_date <='".$end_date."'";
}
$sql="select * from table where true ".$condition_stmt=.";
I would like to know if there is a better way than :
REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('p%a_t*er?', '\\', '\\\\'), '%', '\%'), '_', '\_'), '*', '%'), '?', '_')
To transform standard search patterns * and ? to the LIKE equivalents % and _ in MySQL ?
There isn't a shorter method to perform multiple-character replacements directly in MySQL. There are alternatives such as User-Defined-Functions (UDFs), but I'm doubtful that any would be beneficial to your exact purpose.
My suggestion would be to perform the text replacement prior-to querying the database, if acceptable.
In PHP, this could be done with:
$searchQuery = $_GET['q'];
$searchQuery = str_replace(array('*', '?'), array('%', '_'), $searchQuery);
// perform your query as normal
In ASP, you could try:
string searchQuery = Request.QueryString["q"];
searchQuery = searchQuery.Replace("*", "%").Replace("?", "_");
// perform your query as normal
Though, both method aren't super-short, they do make it a little easier to read and also won't add any time to your db-query. Also, doing the replacement prior to the query will allow you to replace before the string is sanitized so you won't need to replace the \ as you do in your existing query - which saves you one replacement!
Instead of like you can use regexp of Mysql like this:
select * from my_table where col_name regexp 'p%a_t*er?';
While using regexp there is no need to do all those replacements to make your string like friendly.