How to check search param using case statement - sql-server-2008

I have over 20 columns in my table. I have over 10 search fields in a C# dropdownlist. When the user searches, I pass the search fields from dropdownlist and search keywords from textbox. In SQL Server, I want to check what search field is selected like this:
CREATE PROCEDURE [dbo].[SP_Persons_SearchWithKeywords]
(
#SearchField nvarchar(255), #Keywords nvarchar(255)
)
SELECT *
FROM TB_Persons PER
WHERE
(CASE #SearchField
WHEN 'Name' THEN PER.Name = #Keywords
WHEN 'Age' THEN PER.Age = #Keywords
WHEN 'PassportNo' THEN PER.PassportNo = #Keywords
WHEN 'Township' THEN PER.Township = #Keywords
WHEN 'Email' THEN PER.Email = #Keywords
WHEN 'DateOfBirth' THEN PER.DOB = #Keywords
WHEN ....
WHEN ....
)
Is it possible ?
When I execute it, I tried it and not work.
Please help.
Regards,
NNA

Use = and OR/AND instead of CASE:
SELECT * FROM TB_Persons PER
WHERE
( #SearchField = 'Name' AND PER.Name = #Keywords )
OR ( #SearchField = 'Age' AND PER.Age = #Keywords )
OR ( #SearchField = 'PassportNo' AND PER.PassportNo = #Keywords )
.....

Related

Is there a way to mix #variables with placeholders in Perl using DBI and MySQL/MyISAM?

I have a query like this:
SELECT
foo.bar
FROM
foo
WHERE
foo.bang = 0
AND (
CASE
WHEN ? = 2 THEN foo.baz IS NOT NULL
WHEN ? = 1 THEN foo.baz IS NULL
ELSE ? NOT IN (1, 2)
END
)
AND (
(? = 0)
OR
(foo.bang = ?)
)
where the placeholders (?) are used as inputs for filter parameters:
my $query = $aboveQuery;
my ( $results ) = $dbh->DBI::db::selectall_arrayref(
$query,
{ Slice => {} },
$bazFilter,
$bazFilter,
$bazFilter,
$bangFilter,
$bangFilter,
);
This works, but it's not very reader-friendly.
MySQL supports # variables, which would increase readability:
SET #bazFilter = ?; -- passed in via selectall_arrayref or execute;
SET #bangFilter = ?;
SELECT
foo.bar
FROM
foo
WHERE
foo.bang = 0
AND (
CASE
WHEN #bazFilter = 2 THEN foo.baz IS NOT NULL
WHEN #bazFilter = 1 THEN foo.baz IS NULL
ELSE #bazFilter NOT IN (1, 2)
END
)
AND (
(#bangFilter = 0)
OR
(foo.bang = #bangFilter)
);
I'd like to do something like this instead:
my $query = $aboveAtVariablizedQuery;
my ( $results ) = $dbh->DBI::db::selectall_arrayref(
$query,
{ Slice => {} },
$bazFilter,
$bangFilter,
);
but MyISAM apparently won't do multiple statements in a single query.
My google-fu is failing me.
Is there a good way to mix-and-match the #variables with the placeholders?
Do each statement separately, using execute not one of the fetch methods.
# variables are local to the connection, so there is no problem with contamination between threads.
If the goal is to have a single query with no repeated substitutions, then consider:
SELECT foo.bar
FROM ( SELECT baz = ?, bang = ? ) AS init
JOIN foo
WHERE foo.bang = 0
AND (
CASE
WHEN init.baz = 2 THEN foo.baz IS NOT NULL
WHEN init.baz = 1 THEN foo.baz IS NULL
ELSE init.baz NOT IN (1, 2)
END
)
AND (
(init.bang = 0)
OR
(foo.bang = init.bang)
);

Mysql case statement affecting all rows of a table

I have a situaiton that has me a bit confused. im using a case statement to update certain rows of a table. the sql query is below, however if i do not specify a value for the column schema_value, then the query will clear it out to null. Here is a copy of the query and table When the query is run, it will null out initialized and test.
any ideas?
UPDATE vals
SET valu
CASE
When name = 'sitename' THEN '$siteame'
When name = 'street' THEN '$stret'
When name = 'city' THEN '$cit'
When name = 'State' THEN '$sate'
When name = 'zipcode' THEN '$ipcode'
When name = 'phone' THEN '$pone'
When name = 'fax' THEN '$fx'
When name = 'social' THEN '$ocial'
END;
Just add an else statement if nothing matches it should keep the original data
UPDATE schema_vals
SET schema_value =
CASE
When schema_name = 'sitename' THEN '$siteame'
When schema_name = 'street' THEN '$stret'
When schema_name = 'city' THEN '$cit'
When schema_name = 'State' THEN '$sate'
When schema_name = 'zipcode' THEN '$ipcode'
When schema_name = 'phone' THEN '$pone'
When schema_name = 'fax' THEN '$fx'
When schema_name = 'social' THEN '$ocial'
ELSE schema_value
END;

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

Query 2 tables with one field linked to 2 different values

I'm trying to make a SQL query and I have some problems with it.
CREATE table entries (
id_entry INT PRIMARY KEY,
);
CREATE table entry_date (
entry_date_id INT PRIMARY KEY,
entry_id INT,
entry_price INT,
entry_date TEXT,
);
for each entry, there is several dates.
I'd like to select the entries.entry_id where that entry have, for example, the dates '23/03/2013' and '24/03/2013' linked to it.
The two dates are stored into an array:
$data = array('ci' => '23/03/2013', 'co' => '24/03/2013');
I store the dates in text for practical purpose in my treatment.
I use Zend_Db so my query is constructed like that:
$select = $table->select ()->from ( 'entries' )->setIntegrityCheck ( false );
if ($data ['ci'] != NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );
$select->where ( 'entry_dates.entry_date = ?', $data ['ci'] );
}
if ($data ['co']) {
if ($data['ci'] == NULL) {
$select->join ( array (
'entry_dates' => 'entry_dates'
), 'entries.id_entry = entry_dates.entry_id' );}
$select->where ( 'entry_dates.entry_date = ?', $data ['co'] );
}
which gives :
SELECT `entries`.*, `entry_date`.*
FROM `entries`
INNER JOIN `entry_dates`
ON entries.id_entry = entry_dates.entry_id
WHERE (entry_dates.entry_date = '23/03/2013')
AND (entry_dates.entry_date = '24/03/2013')
And, well ... It doesn't work.
When I fetch my $select, I get nothing.
I guess I miss something in my request when I do the WHERE ... AND , what should I do to get the correct output ? The real request being really long, I'd like to avoid another long subselect if possible.
It can be done in two way, either with a self-join on the entry_date table:
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed1
ON entries.id_entry = ed1.entry_id
INNER JOIN `entry_dates` AS ed2
ON entries.id_entry = ed2.entry_id
WHERE ed1.entry_date = '23/03/2013'
AND ed2.entry_date = '24/03/2013'
Or with an aggregate
SELECT `entries`.entry_id
FROM `entries`
INNER JOIN `entry_dates` AS ed
WHERE ed.entry_date = '23/03/2013'
OR ed2.entry_date = '24/03/2013'
GROUP BY `entries`.entry_id
HAVING COUNT(DISTINCT ed.entry_date)=2

Sql (zend db select) of multiple selects

I need a bit of help.
I have (reference?) table with columns: id , user_id , key , value
It is pretty much a user profile table
and I would like to have SQL (I am using zend db table, but general SQL help will do) where I get "all 'user_id's where 'key' is somekey and 'value' is somevalue of that user_id but only if it also matches where 'key' is otherkey and 'value' is othervalue".
In other words I want to get users that have shoes of maker NIKE and color BLACK.
therefore 'key' is shoecolor and 'value' is BLACK and also another row with same user_id has 'key' is shoemaker and 'value' is NIKE.
This is what I could come up with, but doesn't work.
SELECT `user_profiles`.* FROM `user_profiles` WHERE
(`key` = 'shoecolor' AND `value` = 'BLACK') AND
(`key` = 'shoemaker' AND `value` = 'NIKE')
In case someone is knowledgable in zend db:
$where = array('shoecolor' => 'BLACK', 'shoemaker' => 'NIKE');
foreach ($where as $key => $value) {
$sql = $db->quoteInto('key = ?', $key);
$sql .= ' AND ' . $db->quoteInto('value = ?', $value);
$select->where($sql);
}
// make unique result
//$select->groupBy('user_id');
$resultSet = $zendTableInstance->fetchAll($select);
Please Help.
Thanx.
Because the key/value pair is in the row, your query is looking for a key that is 3 AND 4. No value can be 3 and 4 at the same time ;)
SELECT user_profiles.* FROM user_profiles WHERE (key = 3 AND value = 21) AND (key = 4 AND value = 55)
will not work.
You could do a join on yourself, and check for these values?
SELECT user_profiles.*
FROM user_profiles up1
JOIN user_profiles up2 ON up1.user_id = up2.user_id
WHERE
(up1.key = 3 AND up1.value = 21)
AND (up2.key = 4 AND up2.value = 55)