Attempting to add a prefix to a column in SQL Server 2008 - sql-server-2008

I'm trying to add prefix with a condition using 'from' x table then using where to specify the id
For example:
UPDATE tablenameX
SET columnnameX = 'prefix' + columnnameX
FROM tablenameY
WHERE columnnameY = 'id'
I really don't see wheres the issue it refuses to read after columnnameX, what I mean by that is it would execute with no issue, however it ignores the argument I'm trying to use and it applies to every column entry.
I've used a lot of this type of simplistic SQL commands with no issue, I have no idea how to fix it nor do I have the knowledge how to build something that's more complex in nature - I'm a newbie so bear with me.

I'm not sure what the join criteria are because you haven't told us how X and Y are related, but a correlated join looks like this:
UPDATE x
SET x.columnnameX = 'prefix' + x.columnnameX
FROM dbo.tablenameX AS x
INNER JOIN dbo.tablenameY AS y
ON y.< ??? something ??? > = x.< ??? something ???>
WHERE y.columnnameY = 'id';
Or like this:
UPDATE x
SET x.columnnameX = 'prefix' + x.columnnameX
FROM dbo.tablenameX AS x
WHERE EXISTS
(
SELECT 1 FROM dbo.tablenameY AS y
WHERE columnnameY = 'id'
AND y.< ??? something ??? > = x.< ??? something ???>
);

Related

Laravel update based on other value

How can I translate this to be used within the laravel query builder ?
MYSQL
update mytable
set val = val +1
where id = 1
In laravel
$res = DB::table('mytable')
->update(['val' => ?]);
Thanks
Try:
DB::table('mytable')->where('id',1)->increment('val');
the increment method accept as second parameter the amount to sum, if you need to do val = val + 2 you can use ->increment('val', 2).
See this as reference: https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Builder.html#method_increment
In cases where you're doing a more complicated calculation than an increment, you can also do something like this:
DB::table('mytable')->where('id',1)->update(['val' => DB::raw('val * 3')]);
Be careful with DB::raw - it's not going to escape user input for you.

Laravel 4 - SQL query to Laravel Eloquent query

I'm working on a school project and I'm trying to get a query working.
SELECT *
FROM `ziekmeldingen` AS a
WHERE NOT EXISTS
(SELECT *
FROM `ziekmeldingen` AS b
WHERE `ziek` = 1
AND a.personell_id = b.personell_id)
Name of the model: ZiekmeldingenModel
I tried 2 things, both dont work ->
$medewerkers = ZiekmeldingenModel::whereNotExists(function($query)
{
$query->select()->from('ziekmeldingen AS b')->where('ziek', '=', '1')->where('ziekmeldingen.personell_id', '=', 'b.personell_id');
})->get();
return $medewerkers;
And
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->get();
Both of them give back all the results from the table while it should only give back 1 result (I've tested the original query, it works).
EDIT: Forgot to mention I'm using relationships in the model. So the raw solution probably won't work anyway
Found the answer. Had to use a combo of both the things I tried.
$medewerkers = ZiekmeldingenModel::select()
->from(DB::raw('`ziekmeldingen` AS a'))
->whereNotExists(function($query){
$query->select()
->from(DB::raw('`ziekmeldingen` AS b'))
->whereRaw('`ziek` = 1 AND a.personell_id = b.personell_id');
})->get();
return $medewerkers;
Thanks for any help and effort.
Definitely no need for select(). Also no raw in from or whereRaw needed.
The only unusual thing here is raw piece in the where, since you don't want table.field to be bound and treated as string. Also, you can use whereRaw for the whole clause in case you have your tables prefixed, otherwise you would end up with something like DB_PREFIX_a.personell_id, so obviously wrong.
This is how you do it:
$medewerkers = ZiekmeldingenModel::from('ziekmeldingen AS a')
->whereNotExists(function ($q) {
$q->from('ziekmeldingen AS b')
->where('ziek', 1)
->where('a.personell_id', DB::raw('b.personell_id'))
// or:
// ->whereRaw('a.personell_id = b.personell_id');
})->get();
Use the take() method though if you're not ordering your results the record you get back could be any of the results.
$medewerkers = ZiekmeldingenModel::raw('SELECT * FROM `ziekmeldingen` as a WHERE NOT EXISTS ( SELECT * FROM `ziekmeldingen` as b WHERE `ziek` = 1 AND a.personell_id = b.personell_id)')->take(1)->get();

cakePHP: updating mysql table using WHERE clause with multiple conditions

I want to write this SQL statement in cakePHP syntax:
UPDATE students SET status = 'graduated' WHERE age = '23' AND major = 'math';
Now, the way I am trying to do this in cake is
$student->updateAll( array('Student.status' => "'".$rowdata."'"),
array('Student.age' => $current_highest_age,'Student.major' =>
"'".$major."'"));
My variables: $rowdata = 'graduated'; $current_highest_age = 23; and $major = 'math'.
The table is not being updated. Is there a problem with my syntax? I will appreciate your help.
UPDATE ON THE QUESTION:
Actually, I found out where I was wrong in my syntax. The cake code should be 'Student.major' => $major instead of 'Student.major'=>"'".$major."'"
You are double escaping
updateAll expects the fields to be SQL expressions (or simply quoted strings) but the conditions should not be. As such, the query you're going to be generating right now is:
UPDATE
students
SET
status = 'graduated'
WHERE
age = '23' AND
major = '\'math\''
To prevent the extra quotes, which will cause the syntactically-valid statement to match 0 rows, just let Cake take care of your conditions for you as with other methods:
$student->updateAll(
array('Student.status' => "'".$rowdata."'"),
array(
'Student.age' => $current_highest_age,
'Student.major' => $major
)
);
Easy way to update a field of a Model
$this->Testing->updateAll(
array('Testing.door_open_close' => $door_open_close), // value that is updated
array('Testing.id' => $zoneId) // condition field of a Model
);
UPDATE students ...
^^^^^^^^--- student WITH an S
v.s.
array('Student.age')
^^^^^^^ - student WITHOUT an S

In SQL, is there something like: WHERE x = ANY_VALUE?

In a SQL query like this:
SELECT *
FROM MyTable
WHERE x = 5;
is it possible to modify the WHERE condition so that SELECT looks for every value of x? Something like (wrong syntax):
SELECT *
FROM MyTable
WHERE x = ANY_VALUE;
The reason behind this question is that I have to parse and modify some SQL queries through some C++ code I am writing. I know in this case I could just remove or comment the whole WHERE condition, but this is a simplification.
Thank you.
In cases like this, you normally would do something like this:
SELECT *
FROM MyTable
WHERE x = SOME_VALUE OR 1 = 1;
SOME_VALUE is arbitrary, it can be anything matching the type of the column, because the WHERE clause will always be true because of the second part.
You could just omit WHERE clause. :)
While I think it's really the wrong way to go about it (just make the effort to remove the Where), how about where x = x? It won't work if X is null (you'd have to use "x is null or x = x") but don't bother if you know x won't be null.
You can try that:
SELECT *
FROM MyTable
WHERE x = x OR x IS NULL;
You could make your query like this
DECLARE #VALUE as (type of x)
--SET #VALUE = ''
SELECT *
FROM MyTable
WHERE (#VALUE IS NULL OR x = #VALUE);
and your parse would only have to replace
the: --SET #VALUE = '' line for one with the value you want, minus the comment, like: SET #VALUE = 'abc'
hope this helps

IF condition in mysql

I have a contact table I wish to query when a certain condition exists. I tried the query below but am getting a syntax error.
SELECT *
FROM contact_details
WHERE contactDeleted` =0
AND IF ( contactVisibility = "private"
, SELECT * FROM contact_details
WHERE contactUserId = 1
, IF( contactVisibility = "group"
, SELECT * FROM contact_details
WHERE contactGroup = 3
)
)
If I'm understanding your question correctly (which is difficult with the lack of info you've provided. Sample datasets and expected outcomes are typically helpful), then I don't believe you need IFs at all for what you want. The following will return contacts that are not deleted and who either have (visibility = "private" and userId = 1) OR (visibility = "group" and group = 3)
SELECT *
FROM contact_details
WHERE contactDeleted = 0
AND (
(contactVisibility = "public")
OR
(contactVisibility = "private" AND contactUserId = 1)
OR
(contactVisibility = "group" AND contactGroup = 3)
)
I am assuming you want to use the IF() function and not the statement which is for stored functions..
Refer to this link for more information on that.
Notice that you have put 2 select statements in there, where the custom return values are supposed to be. So you are returning a SELECT *... now notice that in your upper level sql statement you have an AND.. so you basically writing AND SELECT *.. which will give you the syntax error.
Try using .. AND x IN (SELECT *) .. to find if x is in the returned values.
Let me also list this link to make use of an existing and well written answer which may also applicable to your question.