Case Statement In Update Query - powershell

This works in SQL Server, but anytime I try to run it in my powershell environment it gives me an error of incorrect syntax near d. What must I alter in order to have this run in powershell?
Function Run-Query
{
param([string[]]$queries)
$server='Server'
$dbname='Database'
$connStr='Server={0};Database={1};Integrated Security=SSPI;' -f $server,$dbname
For ($i = 0; $i -lt $queries.count; $i++)
{
$Command = New-Object System.Data.SqlClient.SqlCommand
$conn=New-Object System.Data.SqlClient.SQLConnection($connStr)
$conn.Open()
$Command.Connection = $conn
$Command.CommandText=$queries[$i]
$Command.ExecuteNonQuery()
$conn.Close()
}
}
$updatequery = "UPDATE d
SET [updatedate] = GETDate(),
[shipped] =
(
CASE WHEN NOT EXISTS(Select 1 *
from [server].[db].[dbo].[viewname] vw
WHERE vw.customername = d.customername)
THEN 'Yes'
ELSE
'PreviousCustomer'
END
)
FROM $fulllocation
WHERE ([shipped] IS NULL)
AND ([managerapproved] IS NOT NULL)
AND [readytoship] IN ('Go', 'Ready', 'Send')"
Run-Query -queries $updatequery

Define your query as a string literal like this:
$updatequery = #"
UPDATE d
SET [updatedate] = GETDate(),
[shipped] =
(
CASE WHEN NOT EXISTS(Select 1
from [server].[db].[dbo].[viewname] vw
WHERE vw.customername = d.customername)
THEN 'Yes'
ELSE
'PreviousCustomer'
END
)
FROM $fulllocation
WHERE ([shipped] IS NULL)
AND ([managerapproved] IS NOT NULL)
AND [readytoship] IN ('Go', 'Ready', 'Send')
"#

Related

Zend 2: How do I execute multiple SQL queries using Zend\Db\Adapter?

Im executing this query:
$query = "
Select * From table1 Where id = 1;
Select * From table2 Where name = 'test';
";
With \Zend\Db\Adapter\Adapter:
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
How can I access the second result?
$rawResult->next() only returns values from first query.
Use two different queries.
/*
* First Query
*/
$query = "
Select * From table1 Where id = 1
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
/*
* Second Query
*/
$query = "
Select * From table2 Where name = 'test'
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
I don't believe it works the way you had it to where two queries in a row are sent this way.
To avoid code duplication you can wrap the duplicated code into a method.
$rawResult1 = $this->getResults("Select * From table1 Where id = 1");
$rawResult2 = $this->getResults("Select * From table2 Where name = 'test'");
function getResults(string $query)
{
$stmt = $this->dbAdapter->query($query);
return $stmt->execute();
}

sqli sum of a column codes not working

I am trying to sum of a column of database table by the following cods, but it's not working:
$sqli = "SELECT sum(total_salary) AS totSalary FROM allsalary WHERE month_session = '$month_name' and org_session = '$org_name' and desig_session = '$desig_name' ORDER BY ID ASC ";
$stmt = $mysqli->prepare($sqli);
$stmt->execute();
$stmt->store_result();
$totl = $stmt->fetch();
$total_salary = $totl['totSalary'];
echo $total_salary;
But I could fetch the table correctly.
Now I want to sum the column named 'total_salary', I need a suggestion.....
You are missing two essential functions here, bind_param() and bind_result()
$sql = "SELECT sum(total_salary) FROM allsalary WHERE month_session = ?
and org_session = ? and desig_session = ? ORDER BY ID ASC";
$stmt = $mysqli->prepare($sql);
$sttmt->bind_paran("sss",$month_name,$org_name,$desig_name);
$stmt->execute();
$stmt->bind_result($total_salary);
$stmt->fetch();
echo $total_salary;

How to make a function use CASE and IFNULL in postgreSQL?

can you tell me how to use CASE and IFNULL in postgre? i'm migrating from sql to postgreSQL, and i want to make a function with this syntax :
SELECT a.furniture_id, a.furniture_brand, a.furniture_cost,
CASE
WHEN furniture_id = f_id THEN a.furniture_content
ELSE ''
END CONTENT
FROM tb_furniture a
WHERE
(IFNULL(a.sale_id,0) = IFNULL(f_id,0) OR (a.furniture_id = f_Id AND IFNULL(a.furniture_content,'') > ''))
AND a.published = 1;
thanks before(y)
This seems to be what you are after, but carefully check the WHERE conditions:
SELECT a.furniture_id, a.furniture_brand, a.furniture_cost,
CASE WHEN a.furniture_id = f_id
THEN a.furniture_content
ELSE ''
END AS content
FROM tb_furniture a
WHERE (coalesce(a.sale_id,0) = coalesce(f_id,0) OR length(content) > 0)
AND a.published = 1;

Zend_DB subselect / subquery how to?

I have this raw sql statement which I am trying to execute through Zend_DB.
$sql = 'SELECT relocationaction.id, relocationaction.vehicle, relocationaction.start, relocationaction.end, relocationaction.return ' .
'FROM relocationaction,
(SELECT vehicle, MAX(end) AS maxend
FROM relocationaction
GROUP BY vehicle) AS co2
WHERE co2.vehicle = relocationaction.vehicle
AND(relocationaction.monitor = 1)
AND (relocationaction.return IS NULL)
AND (start <= ?)
AND relocationaction.end = co2.maxend';
I have found a possible solution using this type of notation, but it is rendered to a totally different and wrong sql statement with joins and strange table names.
$tbl = $this->getDbTable();
$select = $tbl->select()->setIntegrityCheck(false);
$subSelect = $select->from('relocationaction', array('vehicle', 'maxend' => 'MAX(relocationaction.end)'))
->group('vehicle');
$subSelectString = '(' . $subSelect->__toString() . ')';
$select ->from(
array('relocationaction'), array('id', 'date' => 'start', 'enddate' => 'end', 'return'),
array('co2' => $subSelectString)
)
->joinLeft('exhibitvehicle', 'exhibitvehicle.id = relocationaction.vehicle', array())
->where('co2.vehicle = relocationaction.vehicle')
->where('relocationaction.monitor = 1')
->where('relocationaction.return IS NULL')
->where('start <= ?', $start->get('yyyy-MM-dd'))
->where('relocationaction.end = co2.maxend');
Can anyone please give me a hint?
Thanks
Jesse
UPDATE
This is the result of the second expression (total rubbish)
SELECT `relocationaction`.`vehicle`,
MAX(relocationaction.end) AS `maxend`,
`relocationaction_2`.`id`,
`relocationaction_2`.`start` AS `date`,
`relocationaction_2`.`end` AS `enddate`,
`relocationaction_2`.`return`
FROM `relocationaction`
INNER JOIN `(
SELECT ``relocationaction``.``vehicle``,
MAX(relocationaction.end) AS ``maxend`` FROM ``relocationaction`` GROUP BY ``vehicle``)`.`relocationaction` AS `relocationaction_2`
LEFT JOIN `exhibitvehicle` ON exhibitvehicle.id = relocationaction.vehicle
WHERE (col2.vehicle = relocationaction.vehicle)
AND (relocationaction.monitor = 1)
AND (relocationaction.return IS NULL)
AND (start <= '2013-05-08')
AND (relocationaction.end = col2.maxend)
GROUP BY `vehicle`
If you use a string in from(), Zend_Db_Select will consider it to be a table name so it escapes it.
The solution is to wrap your subselect into a Zend_Db_Expr.
$tbl = $this->getDbTable();
$select = $tbl->select()->setIntegrityCheck(false);
$subSelect = $select->from('relocationaction', array('vehicle', 'maxend' => 'MAX(relocationaction.end)'))
->group('vehicle');
$subSelectString = '(' . $subSelect->__toString() . ')';
$select ->from(
array('relocationaction'), array('id', 'date' => 'start', 'enddate' => 'end', 'return'),
array('co2' => new Zend_Db_Expr($subSelectString))
)
->joinLeft('exhibitvehicle', 'exhibitvehicle.id = relocationaction.vehicle', array())
->where('co2.vehicle = relocationaction.vehicle')
->where('relocationaction.monitor = 1')
->where('relocationaction.return IS NULL')
->where('start <= ?', $start->get('yyyy-MM-dd'))
->where('relocationaction.end = co2.maxend');
Ok here we go. I tried hard to find a solution with Zend_Db_Table but failed big time. That's why I finally did it with PDO, as suggested by #user466764. Thanks for your help.
$tbl = $this->getDbTable();
$query = 'SELECT relocationaction.id,
relocationaction.vehicle,
relocationaction.start,
relocationaction.end,
relocationaction.return
FROM relocationaction
(SELECT vehicle, MAX(end) AS maxend
FROM relocationaction
GROUP BY vehicle) AS co2
WHERE co2.vehicle = relocationaction.vehicle
AND(relocationaction.monitor = 1)
AND (relocationaction.return IS NULL)
AND (start <= "' . $start->get('yyyy-MM-dd') . '")
AND relocationaction.end = co2.maxend';
$sth = $tbl->getAdapter()->prepare($query);
$sth->execute();
$entries = $sth->fetchAll();

OR clause in Zend DB update?

I'd like to do a Zend db update with an OR clause. What would be the equivalent statement to:
UPDATE mail
SET message_read = 1
WHERE id = 5
OR id = 10
When calling Zend_Db_Adapter::update(), multiple WHERE conditions will automatically be combined using AND (line 698 of Zend/Db/Adapter/Abstract.php in function _whereExpr).
You can get around this by creating your own Zend_Db_Expr which you will use as the WHERE condition and it will be left untouched.
For example:
$where[] = new Zend_Db_Expr(
$table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
$table->getAdapter()->quoteInto('id = ?', 10)
);
// resulting expression:
// WHERE (id = 5 OR id = 10)
$table->update($data, $where);
If you had additional WHERE conditions, they would be combined with the OR condition by an AND.
Example:
$where[] = new Zend_Db_Expr(
$table->getAdapter()->quoteInto('id = ?', 5) . ' OR ' .
$table->getAdapter()->quoteInto('id = ?', 10)
);
$where[] = $table->getAdapter()->quoteInto('type = ?', 'sometype');
// resulting expression:
// WHERE (id = 5 OR id = 10) AND (type = 'sometype')
->where() will add a where clause to the query and will put an 'AND'. There is an orWhere method that exists to do that.
$select = $this->select();
$select->where('id = 5');
$select->orWhere('id = 10');
$this->fetchAll($select);