How to do a select statement query with comma separator? - range

I need to do a simple query, Select Statement
I want to search in Table all record with value "ValueA, ValueB".
If I use this code, not work well:
String255 valueToFilter;
valueToFilter = 'ValueA, ValueB';
select count (RecId) from MyTable
where MyTable.Field like valueToFilter ;
But not working, I need to keep all record with value "ValueA" or "ValueB", if in the file there is value like : "ValueA, ValueC" I want to get too.
I don't know the number of values (valueToFilter).
Thanks!

From my point of view the easiest way to accomplish this is to split your filter string:
String255 valueToFilterA = 'ValueA';
String255 valueToFilterB = 'ValueB';
;
select count (RecId) from MyTable
where MyTable.Field like valueToFilterA
|| MyTable.Field like valueToFilterB;
If you don't know the number of values you should use query object to add ranges dynamically:
Query query = new Query();
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange queryRange;
container conValues;
;
qbds = query.addDataSource(tableNum(MyTable));
for (i = 1; i <= conlen(conValues); i++)
{
queryRange = qbds.addRange(fieldNum(MyTable, Field));
queryRange.value(SysQuery::valueLike(conPeek(conValues, i)));
}
queryRun = new QueryRun(query);
info(strFmt("Records count %1", SysQuery::countTotal(queryRun)));

Related

Codeigniter: How to increase active records in the for loop?

I'm using PostgreSQL and I have a table which includes week numbers of the year in its columns. I try to update by increasing these columns' values in nested loops.
I have the following query which attempts to increase the related field of a record.
foreach ( $updateVotes as $key => $value ) {
for ( $week = 1; $week < 53 ; $week++) {
$increaseValue = $value['week_'.$week];
$this->db->set("week_".$week , "week_".$week. " +".$increaseValue, "FALSE");
}
$this->db->where('id', $id)
->update('votes');
}
To achieve my aim, I need output like the one below:
UPDATE "votes"
SET week_1 = week_1 +20,
week_2 = week_2 +50,
...
WHERE id = 1
However, when I run the query, it produces the following SQL:
UPDATE "votes"
SET "week_1" = 'week_1 +20',
"week_2" = 'week_2 +50',
...
WHERE id = 1
As it also produces single quotes, it throws errors like this:
column 'week_1 +20' cannot found
How can I escape these single quotes and run the query successfully?
According to the official document here, you should pass FALSE (Bool) instead of "FALSE" (String) like this
$this->db->set("week_".$week , "week_".$week. " +".$increaseValue, FALSE);
Hope this helps!
Remove Double quotes from "FALSE" into FALSE

getting the 1st row in a database

I want to get the 1st row of the result depends on which build the room is. For example Building 1 have 1-200 rooms and Building 2 have 201-400 rooms. The code I tried is below. I have used the MIN in the where clause but I got all the rooms instead of having one.
$query = $this->db->query("SELECT * FROM `ha_utility_reading`");
if ($query->num_rows == 0) {
echo "some data match";
$lastroom = $this->db->select("*")->from("rooms")
->where("(SELECT MIN(room_num) FROM ha_rooms) and bldg_num = '$bldg_num'")
->get()->result_array();
foreach($lastroom as $key => $test) {
$output['room_num'][] = $test['room_num'];
json_encode($output);
}
You get all the rows because you need a group by clause. Anyway, the best way to do this is just adding this to your query:
order by room_num asc limit 1;
Try this,
select * from rooms order by room_num asc limit 1;

how to convert count(*) and group by queries to yii and fetch data from it

I want to convert this query in yii
SELECT count(*) AS cnt, date(dt) FROM tbl_log where status=2 GROUP BY date(dt)
and fetch data from that. I try this command (dt is datetime field):
$criteria = new CDbCriteria();
$criteria->select = 'count(*) as cnt, date(dt)';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
but no data will fetch!
wath can I do to get data?
Probably you see no data because you need assign data to model attributes which doesn't exist.
$criteria = new CDbCriteria();
$criteria->select = 'count(*) AS cnt, date(dt) AS dateVar';
$criteria->group = 'date(dt)';
$criteria->condition = 'status= 2';
$visit_per_day = $this->findAll($criteria);
This means that your model must have attributes cnt and dateVar in order to show your data. If you need custom query then check Hearaman's answer.
Try this below code
$logs = Yii::app()->db->createCommand()
->select('COUNT(*) as cnt')
->from('tbl_log') //Your Table name
->group('date')
->where('status=2') // Write your where condition here
->queryAll(); //Will get the all selected rows from table
Number of visitor are:
echo count($logs);
Apart from using cDbCriteria, to do the same check this link http://www.yiiframework.com/forum/index.php/topic/10662-count-on-a-findall-query/
If you use Yii2 and have a model based on table tbl_log, you can do it in model style like that:
$status = 2;
$result = Model::find()
->select('count(*) as cnt, date(dt)')
->groupBy('date(dt)')
->where('status = :status')
->params([':status' => $status ])
->all();

FQL WHERE IN with Null feedback in the array

I'm trying the command below:
SELECT * FROM mytable WHERE field IN(1,2,3, NULL, 5)
and the result is {r1,r2,r3}
I want {r1,r2,r3,NULL,r4}, how can I do that?
Thank you!
You can't. Facebook automatically filters out NULL results from the rows. There is also no guarantee that the results will be in the same order as the arguments you passed in your IN criteria.
You also can't SELECT * in FQL. You have to individually select fields to return.
You'll need to do something like this:
THINGS_TO_FIND = array (1,2,3,NULL,5)
RESULT = FQL_URL + urlencode('SELECT field1, field2 FROM table WHERE field1 IN ' + THINGS_TO_FIND')
foreach (THING in THINGS_TO_FIND) {
foreach (ITEM in RESULT) {
if THING == ITEM->field1 then OUTPUT->field1 = ITEM->field2
}
}

ADO.NET: How to have N parameters?

i need to mark a batch of rows in the database as "processed".
In the olden days, when things were easier, i would create some SQL that said:
UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (
"2010-10-07 22:02:13.327",
"2010-10-07 22:02:14.213",
"2010-10-07 22:02:15.595",
...
"2010-10-07 23:03:36.981")
by looping through a list of dates:
sql = "UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (";
foreach (DateTime datetime in dates)
{
sql = sql + CRLF+ DateTimeToSql(datetime)+",";
}
sql = sql+")";
And issue the SQL:
ExecuteNonQuery(connection, sql);
And all was good.
Now i want to try to do things the hard way; i want to try to use parameters:
sql = ???;
command.CommandText = sql;
DbCommand command = connection.CreateCommand();
foreach (DateTime datetime in readings)
{
command.Parameters.Add(new SqlParameter(???, SqlDbType.DateTime) {Value = datetime});
}
using (DbTransaction transaction = connection.BeginTransaction())
{
command.Transaction = transaction;
command.ExecuteNonQuery();
transaction.Commit();
}
The only trick is what to put in the sql string, and what to put in each iteration of the parameters loop. They need some name.
What's the recommended way to name arbitrary number of parameters?
I think what you could do is something like this:-
sql = "UPDATE Readings SET IsProcessed = 1 WHERE ReadingDateTime IN (";
for (int count=0; count<dates.Length; count++)
{
sql = sql + CRLF + ":param" + count;
}
sql = sql+")";
for (int count=0; count<dates.Length; count++)
{
command.Parameters.Add(new SqlParameter(":param" + count, SqlDbType.DateTime) {Value = datetime});
}
However, i think that having parameters specifically in this scenario is kind of unnecessary.
Considering that your dynamic values are dates and not strings, you can instead validate the dates directly using a TryParse to ensure that they are the correct datatype before you append them in your original solution!!
I dont know if you are achieving anything extra over that by using parameters in this case.
You can go as minimal as you like: the provider will accept parameters named #0, #1, etc. But if you want to be more descriptive, just use a base name of #ReadingDateTime, with an integer suffix from 0..n. Easy peasy.