How to use If statement in addCondition, YII - sql

I have some conditions to hand on to my dataprovider. Now, my last condition I want only to take place only when the field "edit" is set to true -> In this case I want to check if the editConfirmed field 'editBevestigd' is set to true. If the 'edit' field is empty I don't want to add this last condition.
$criteria->addCondition('bevestigd = 1');
$criteria->addCondition('IF(edit = 1) editBevestigd = 1');
What is the best way to handle this. Can I do this in YII (problem here is that the record is not known yet). Or how do I write this in SQL (I know this last condition isn't right right now..)?
Thanks in advance!

If i right understand what you want then you should use this condition:
WHERE (edit = 1 AND editBevestigd = 1) OR edit = 0
Thus, the condition becomes:
$criteria->addCondition('(edit = 1 AND editBevestigd = 1) OR edit = 0');

You can try like that
//for php variable set or not
if($edit==1){
$criteria->addCondition('editBevestigd=1');
}
//for column set or not
$criteria->addCondition('edit IS NOT NULL AND editBevestigd=1');

Related

Struggling with simple boolean WHERE clause

Tired brain - perhaps you can help.
My table has two bit fields:
1) TestedByPCL and
2) TestedBySPC.
Both may = 1.
The user interface has two corresponding check boxes. In the code I convert the checks to int.
int TestedBySPC = SearchSPC ? 1 : 0;
int TestedByPCL = SearchPCL ? 1 : 0;
My WHERE clause looks something like this:
WHERE TestedByPCL = {TestedByPCL.ToString()} AND TestedBySPC = {TestedBySPC.ToString()}
The problem is when only one checkbox is selected I want to return rows having the corresponding field set to 1 or both fields set to 1.
Now when both fields are set to 1 my WHERE clause requires both check boxes to be checked instead of only one.
So, if one checkbox is ticked return records with with that field = 1 , regardless of whether the other field = 1.
Second attempt (I think I've got it now):
WHERE ((TestedByPCL = {chkTestedByPCL.IsChecked} AND TestedBySPC = {chkTestedBySPC.IsChecked})
OR
(TestedByPCL = 1 AND TestedBySPC = 1 AND 1 IN ({chkTestedByPCL.IsChecked}, {chkTestedBySPC.IsChecked})))
Misunderstood the question.
Change the AND to an OR:
WHERE TestedByPCL = {chkTestedByPCL.IsChecked} OR TestedBySPC = {chkTestedBySPC.IsChecked}
Also:
SQL Server does not have a Boolean data type, it's closest option is a bit data type.
The usage of curly brackets suggests using string concatenations to build your where clause. This might not be a big deal when you're handling checkboxes but it's a security risk when handling free text input as it's an open door for SQL injection attacks. Better use parameters whenever you can.

SQL statement with conditionals

I'm currently building a food application which has users select a range of options (perishable, non-perishable ) and (snack, produce or meal) via a set of radio buttons. I'm currently using node.js and sqlite 3 to query a database to determine which entries to return to the user after they search the database.
I want to write a query such that when the booleans from the client-side are sent over to the server, the server will choose the entries such that perishable if perishable is set to true on the client that the query will find just the perishable items and vice-versa. I also want the same functionality with
Example:
perishable = request.perishable.
non-perishable = request.non-perishable
snack = request.non-perishable
meal = request.non-perishable
produce = request.non-perishable.
var q = 'SELECT * FROM posts WHERE available == true AND (if perishable is true all rows where the perishable column is set to true... etc );
Why not just change the query based on perishable?
var q = 'SELECT * FROM posts WHERE available == true';
if (perishable)
q += ' AND perishable == true';
You can do it with a CASE WHEN syntax in WHERE:
WHERE perishable IS CASE WHEN [condition] THEN TRUE ELSE FALSE END
Just a quick tip. Search for this syntax in your database documentation.

Excel MS Query - How to write parameter equals "" or show all in SQL query

Just finished writing an SQL script in the MS-Query and I'm having difficulty trying to get it to work.
What I'm after is the equivalent of this SQL where clause:
AND ((examplefield = #Para) or (#Para = ''))
So if parameter = something in the field, only show that or if the parameter = blank then show all results.
So far this is what I have which works fine if I want to select a particular item, now I just need to include the additional if blank show all.
AND (`'Project Master List$'`.`Type of Work`= ?)
This unfortunately doesn't work.
AND ((`'Project Master List$'`.`Type of Work`= ?) OR (? = ""))
Any suggestions?
Try a case?
Case When ?="" THEN
'docode'
WHEN ?="OtherValue" THEN
'DoCode'
Else
'DoCode '
End
The IIF Example:
iif(?="",
iif(?="OtherValue",ReturnSomethingTrue,ReturnSomethingFalse)
,ReturnSomethingTrue,ReturnsomethingFalse)
I looked back at my original question and realised I wrapped the where clause in the wrong quotes. See below
Wrong statement
AND ((`'Project Master List$'`.`Type of Work`= ?) OR (? = ""))
Correct statement
AND (`'Project Master List$'`.`Type of Work`= ? OR ? = '')
Once I'd made the change right at the end of the clause it worked.

Add up value using database field value with savefield in cakephp

my question is pretty simple but hard to find an answer for though search engines.
I simply want to update a field in the database, using that fields old value to add another value. I'm using the following at the moment:
$this->Advertisement->saveField('total_views', '(total_views + 1)', false);
But this gives me the next query:
UPDATE `advertisement` SET `total_views` = '(total_views +1)', `modified` = '2011-08-26 10:44:58' WHERE `advertisement`.`id` = 16
This is wrong and it should be:
UPDATE `advertisement` SET `total_views` = (total_views +1), `modified` = '2011-08-26 10:44:58' WHERE `advertisement`.`id` = 16
The problem is where it puts (total_views +1) between quotes.
Does anyone have an idea on how to get this working?
$this->Advertisement->updateAll(
array('Advertisement.total_views' => 'Advertisement.total_views + 1'),
array('Advertisement.id' => 1)
);
Just in case anyone else gets stuck with this, the spaces in the query are important.
works: Advertisement.total_views + 1
does not work: Advertisement.total_views+1
$this->Advertisement->updateAll(array('Advertisement.total_views'=>'Advertisement.total_views+1'), array('Advertisement.id'=>$id));
I found that for a similar issue I was able to resolve it in the following manner,
$this->Advertisement->updateAll(
array('Advertisement.total_views = Advertisement.total_views + 1'),
array('Advertisement.id' => 1)
);

My simple sql update query is not working right :(

I've got a simple sql query that is trying to update a single row. The code came from some Linq-to-sql code (i used Profiler to grab it), but please don't worry about the source (L2S) ... that's irrelivant to the question.
Now, when i try and do an update with the where clause, I get 0 rows updated.
I then try and do a select with the same where clause. i get a single result back. Ok, so the data is there.
It's only when i turn off some of the where clause statements does the query finally work. I just don't get it :(
I can't really explain it. So I made a video showing this.
Please watch the video on YouTube here.
Can anyone help? It's really weird :(
Database is MS-SQL 2008.
-- UPDATE
The sql i'm trying to execute (after i've cleaned it up from L2S)..
update tblBoardPost
set IsSticky = 1
where IdBoardPost = 1278
and IdAddress = 212787
and Subject = N'ttreterte'
and Banner is null
and UniqueSubject = N'ttreterte5'
AND (NOT ([IsAnnouncement] = 1))
AND (NOT ([IsSticky] = 1))
AND (NOT ([IsLocked] = 1))
and IsVisible = 1
and IdUserModified = 1
AND [IdNewsArticle] IS NULL
AND [IdList] IS NULL
(note: yes, i know the NOT (blah = 1)) is weird, but that's L2S that made that.
Update 2:
The code in the video is being ran in a transaction/rollback trans. this means that if i do run one of those weird scenario's that works, the change works .. but the rollback undoes it .. so when i run it a 2nd time .. the original value has been returned to the db row.
Also, in the vid, the select query is not exactly the same as the update query .. because i've been trying so many permutations (with no luck) .. so by the time i made the vid .. i forgot to show the original code. That said, the same code in both the select statement and the update/where statement (when i copy/paste on my machine) reproduces the exact same probs :(
Update 2 :)
As per Lieven's request, here's the screenshot showing the code and then the results.
alt text http://img196.imageshack.us/img196/7111/lieven.png
I checked your video, and you should try the same SQL conditions, that you used to return one row in your select query, in your update query. The conditions in the two SQL statements in your video aren't the same, and I don't really care why; they're not apples to apples.
Just copy and paste the working WHERE clause over the non-working one.
In the video, your select goes like
and not IsAnnouncement = 1
wich gives entirely different results as in your update
and not (IsAnnouncement = 1)
It seems you are suffering from an operator precedence issue .
Edit
as the queries don't match in your video and although you say they have matched could you copy paste following script and let us know if or if they do not give you the same results? (I for one would have a hard time believing that the rows affected would differ)
begin tran
select *
from tblBoardPost
where
IdBoardPost = 1278
and IdAddress = 212787
and Subject = N'ttreterte'
and Banner is null
and UniqueSubject = N'ttreterte5'
AND (NOT ([IsAnnouncement] = 1))
AND (NOT ([IsSticky] = 1))
AND (NOT ([IsLocked] = 1))
and IsVisible = 1
and IdUserModified = 1
AND [IdNewsArticle] IS NULL
AND [IdList] IS NULL
update tblBoardPost
set IsSticky = 1
where
IdBoardPost = 1278
and IdAddress = 212787
and Subject = N'ttreterte'
and Banner is null
and UniqueSubject = N'ttreterte5'
AND (NOT ([IsAnnouncement] = 1))
AND (NOT ([IsSticky] = 1))
AND (NOT ([IsLocked] = 1))
and IsVisible = 1
and IdUserModified = 1
AND [IdNewsArticle] IS NULL
AND [IdList] IS NULL
rollback tran