UPDATE SQL column based on values of another column. (It's not that simple) - sql

I am trying to update a column with a value of a different column under certain circumstances. It's complicated. I've tried to figure this out on my own for a weeks now. (on and off)
Here is how it currently looks:
I Need a SQL statement that will look for the LotNo at OperationCode 1280 and assign it for all values with the same CastTID.
Here is what it should look like after
I would really appreciate any help! This is my first post, if iv'e left out anything important please let me know so that I can help you help me.

You can use a join in your update statement to make this easier.
update t
set CastLotNo = t2.LotNo
from yourTable t
inner join yourTable t2 on t2.CastTID = t.CastTID and t2.OperationCode = 1280

UPDATE `myTable` SET `CastLotNo` = (SELECT `LotNo` FROM `MyTable` WHERE `OperationCode` = '1280' LIMIT 1) WHERE `CastTID` = (SELECT `CastTID` FROM `MyTable` WHERE `OperationCode` = '1280' LIMIT 1)
It seems like you could use something like that. I can't test this at the moment, so let me know if it needs tweaking.

WITH cte as (
SELECT CastTID, LotNo
FROM Table1
WHERE OperationCode = 1280
)
UPDATE myTable T
SET CastLotNo = (SELECT C.LotNo as CastLotNo
FROM cte C
WHERE C.CastTID = T.CastTID)

Related

Using ISNULL in SQL LEFT JOIN to check if the result is null, and if it is, use another value to join

I have a SQL select with a where clause where i want to check if the result is null, and if it is null I want to use another value in the where clause, but i get 0 rows results, even though i know i should get a row as result.
Heres my (updated) SQL code:
DECLARE #LanguageCode NVARCHAR(3);
SET #LanguageCode = 'FR'
SELECT
wi.WorkItemId,
ds.DisplayString AS Team
FROM dbo.WorkItem AS wi
LEFT JOIN dbo.DisplayString AS ds ON ds.ElementID = wi.TierId AND ds.LocaleID = ISNULL(#LanguageCode, 'ENU')
The code above returns data for "#LanguageCode" when there is data to return, but it does not switch to use 'ENU' when there is no data. Thats the problem!
This is also just a sample since this is part of a larger query with lots of left joins where i need the same functionality against "LocaleID". I'm hoping there would be something easy solution to this like the code above.
To clarify what i want to achieve, if the c.LocaleID = #LanguageCode returns null rows i want to use the hardcoded value as in c.LocaleID = ENU.
If i don't use the ISNULL function and only use 'ENU' it returns the expected result.
I would appreciate any help. Thanks.
If I understand correctly, you want one row, either with the specified language code or 'ENU'. If so, use filtering and ORDER BY:
SELECT TOP (1) c.*
FROM dbo.column1 c
WHERE c.rowID = '1234-1234-1234' AND
c.LocaleID IN (#LanguageCode, 'ENU')
ORDER BY (CASE WHEN c.LocaleID = #LanguageCode THEN 1 ELSE 2 END)
I think you're looking for this
select coalesce((SELECT rowID FROM dbo.column1 where c.rowID = '1234-1234-1234' and LocaleID = #LanguageCode),
(SELECT rowID FROM dbo.column1 where c.rowID = '1234-1234-1234' and LocaleID = 'ENU'));
I believe you are looking for something like this:
SELECT *
FROM table_name c
WHERE c.LocaleID =
case when (select count(*)
from table_name tn
where tn.LocaleID = #LanguageCode) = 0 then
'ENU'
else
#LanguageCode
end;
Here is the demo.
Here is a new demo: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=624100ee44f89decc4c6383e92d0a016
In the new demo I have added some more code to show how to use it in left join as a part of the join condition and also I have added the code to show how to use it in where clause when joining two tables and I believe it belongs in the where clause...

Update table only if value does not exist in a specific column

I want to update a column (variableA) in a table (myTable) only when
There is no dataset with this #variableA in the variableA column
There is already a dataset with #variableB in the variableB column and with 'DUMMY' in the variableA column
FYI: Another interface inserts the 'DUMMY' datasets before and I later need to update them with the real variables/numbers.
The code below is already working fine but I am wondering if there is a more "elegant" solution to do this. I want to avoid/change the last line ("SELECT COUNT(*)" etc.)
DECLARE #variableA nvarchar(10) = '12345'
DECLARE #variableB nvarchar(10) = '67890'
UPDATE TOP (1) myTable
SET variableA = #variableA,
timestamp = GETDATE()
WHERE variableB = #variableB
AND variableA = 'DUMMY'
AND (SELECT COUNT(*) FROM myTable WHERE variableA = #variableA) = 0
Can you please help me to find a smarter solution instead of this last line?
you can use not exists operator like this
not exists (SELECT 1 FROM myTable WHERE variableA = #variableA)
and if it again slow you can set index I_my_Table_variableA by your variableA column and it will be more faster(you can set index by variable because it almost unique and it will be good index)
Well, I would write it like this:
UPDATE myTable
SET variableA = #variableA,
timestamp = GETDATE()
WHERE variableB = #variableB
AND variableA = 'DUMMY'
AND NOT EXISTS (
SELECT 1
FROM myTable
WHERE variableA = #variableA
)
First, Using TOP without specifing ORDER BY is a mistake, since database tables are unsorted by nature, this actually means that you might get unexpected results.
Second, changing the (select count) > 0 to exists(select...) might improve performance (unless the optimizer is smart enough to use the same execution plan for both cases)
Also, for your future questions - Please avoid using images to show us sample data and desired results. Use DDL+DML to show sample data, and text to show desired results. If you do that, we can copy your sample data to a test environment and actually test the answers before posting them.

Find multiple SQL columns and update based on defined data listed in query

I have an update query in which I am trying to locate data in a column from a single table. All while taking other defined data listed in the query to update another column in the same table once a match has been found with that original search. Below is an example of my update statement. My end goal is to find '003447710' then update AltId to '540112'
UPDATE Site
SET AltId = ('540112'
'540129'
'540142'
'540143')
WHERE CCMFStatus in ('003447710',
'002754540',
'003564370',
'005942870')
I am sure there may already be something like this out there but I am really having trouble on an easy method on how to do this quickly and accurately.
Try this
update site
set altid = a.altid
from
(select altid,CCMFstatus from site) as a
where site.CCMFstatus = a.CCMFstatus
The best way might be multiple update statements:
UPDATE Site
SET AltId = '540112'
WHERE CCMFStatus = '003447710';
And so on.
If not, you can do this with a giant case statement or a join:
WITH values as (
SELECT '003447710' as oldstatus, '540112' as newaltid UNION ALL
SELECT '002754540', '540129' UNION ALL
SELECT '003564370', '540142' UNION ALL
SELECT '005942870', '540143'
)
UPDATE s
SET AltId = va.newaltid
FROM site s JOIN
values v
ON s.CCMFStatus = v.oldstatus;
If you already have the values in a table, then you don't need the WITH statement. You can just use the table.
Have you tried using CASE statement?
UPDATE SITE SET AltID = (CASE
WHEN CCMFStatus = '003447710' THEN '540112'
WHEN CCMFStatus = '002754540' THEN '540129'
END)
WHERE
CCMFStatus in ('003447710', '002754540', '003564370', '005942870');
BR,

SQL Update with select MIN from specific group in one table

Im really new to SQL. I searched for an answer that would match my requirements AND I would understand what has been done- I failed obv. So here it goes:
I am making a programm that would keep data for marathon tournament. So I have a table StageResults with columns: StageNo ParticipantNumber ParticipantGroup Time(as in distance time in full sec's thus int) and Points
An example would look like:
- 1|01|M21|500|X
- 1|22|M21|550|X
- 1|45|M21|530|X
- 1|47|F09|600|X
- 1|09|F09|630|X
- 2|01|M21|515|X
- 2|45|M21|520|X
So I want the fastest member of each group in each stage to get 1000 points. In the back of my head I feel, that I could just write 1 single query for this, I tried for several hours.
Best that I have right now is this:
SELECT c1.ParticipantNumber, c1.ParticipantGroup, c1.Time
FROM StageResults AS c1
LEFT JOIN StageResults AS c2
ON c1.StageNo = c2.StageNo
AND c1.ParticipantGroup = c2.ParticipantGroup
AND c1.Time < c2.Time;
I used this under INSERT statement. No syntax errors but error, that I am trying to insert a duplicate primary key. I think this can be solved by adding GROUP BY statement. So I havent really tested this.
I would ultimately like to set 1000 points for fastest participant in each run(stage) and each group(I mean it should happen automatically). And then based on the fastest guy, calculate points for all other guys.(But thats later and if i figure out how to add these 1k pts, I think ill manage)
So I have to add this logic inside UPDATE statement. I am not able to. Im just lost.
Any advice is welcome. Maybe im thinking in the wrong direction completely on how to do this.
Any help will be much appreciated.
The query that identifies the rows might look like this:
select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
);
The question is then how you turn this into an update. For MySQL, you would do:
update table StageResults sr join
(select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
)
) toupdate
on toupdate.ParticpantNumber = sr.ParticpantNumber
set sr.points = sr.points + 1000;
The syntax for SQL Server would be a bit different, but your question is tagged MySQL.
EDIT:
For SQL Server:
with toupdate as (select t.*
from table t
where not exists (select 1
from table t2
where t2.ParticipantGroup = t.ParticipantGroup and
t2.StageNo = t.StageNo and
t2.time < t.time
)
)
update toupdate
set points = points + 1000;

Oracle SQL update

I've tried searching for this particular topic here, but haven't found the answer... Anyway, my aim is to update table (let's call it t_item), specifically column owner_id with values depending on another table (t_item_geo which is in turn linked to t_geo).
I'm not entirely sure whether the syntax below is actually valid for update statements.
UPDATE t_item SET owner_id= 6993 WHERE t_item.owner_id in
(SELECT t_item.owner_id FROM
t_item,
t_item_geo,
t_geo
WHERE
t_item.id = t_item_geo.item_id and
t_item_geo.geo_id = t_geo.id and
t_item.owner_id in (SELECT id FROM t_user WHERE network_id='fffffff') and
t_geo.id in (SELECT id FROM t_geo WHERE full_name = 'yyyyyyy')
);
Anyway, my problem with this query is that it updates far more rows than it should - if I separate just the select statement Oracle returns ~750 rows but the udpate itself updates more than 4000 rows. It's almost as if the condition was completely ignored - which would point me to perhaps incorrect syntax.
I need to update specific value in the table based on the select from few other 'joined' tables. Hope it makes sense.
Thanks for any contribution!
UPDATE: sorry - maybe it wasn't clear from the question itself, but the correct number of edited items should be ~750 and not ~4000. Thanks!
try this
MERGE INTO t_item
USING
(
SELECT t_item.owner_id FROM
t_item,
t_item_geo,
t_geo,
t_item.rowid rowid_sub
WHERE
t_item.id = t_item_geo.item_id and
t_item_geo.geo_id = t_geo.id and
t_item.owner_id in (SELECT id FROM t_user WHERE network_id='fffffff') and
t_geo.id in (SELECT id FROM t_geo WHERE full_name = 'yyyyyyy')
) on (rowid = rowid_sub)
WHEN MATCHED THEN
UPDATE SET owner_id= 6993;