How to update more than one column in SQL? - sql

I have a SQL which I am using for updating many rows at the same time using a complex case condition. Currently, I am setting 2 column using the same CASE condition.
For example, I need to do something like:
UPDATE MyTable
SET([MyColumn1], [MyColumn2]) = ('','')
What I am doing now is:
UPDATE MyTable
SET [MyColumn1] = COMPLEX CASE RETURN STRING,
[MyColumn2] = 100% SAME COMPLEX CASE RETURN A Different STRING
I tried but getting error. Is this is possible in SQL SERVER?
It is supported in IBM Db, http://publib.boulder.ibm.com/infocenter/idshelp/v111/index.jsp?topic=/com.ibm.sqls.doc/sqls919.htm
But it seems there is no support in SQL Server

Update command syntax is:
UPDATE table_name
SET column1=value1,column2=value2,...
WHERE some_column=some_value;

update mytable
SET [MyColumn1] = COMPLEX CASE RETURN STRING,
[MyColumn2] = 100% SAME COMPLEX CASE RETURN A Different STRING
WHERE some_column=some_value;// please have the where condition
then only we can update the corresponding raw.
updating means we are changing some existing values so we need to provide the location where we want this change,for that we can use the where condition..
example
update author
set name="onv kurup"
set book="oralude"
where authorid=112;
if we are not giving the where condition all the data of the table will be get updated with same value in the update query we have given

After searching a lot, I have found the answer,
update table1
set col1 = a.col1, col2 = a.col2, col3 = a.col3 from
table1 as a Join on tablefunction
where table1.col1 <expression>
http://geekswithblogs.net/phoenix/archive/2009/10/13/update-multiple-columns-on-sql-server.aspx

Related

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 server if statement not working

Can anyone advise me as to what is wrong with the following SQL server update statement:
IF (SELECT * FROM TBL_SystemParameter WHERE code='SOUND_WRONG_GARMENT') = ''
GO
UPDATE TBL_SystemParameter
SET [Value] = 'Ping.wav'
WHERE ID = (SELECT ID
FROM TBL_SystemParameter
WHERE code = 'SOUND_WRONG_GARMENT')
You don't need an if statement - you can just run the update statement, and if the subquery returns no rows, no rows will be updated. The if won't really save anything - you're performing two queries instead of one.
You either want
UPDATE TBL_SystemParameter
SET [Value] = 'Ping.wav'
WHERE ID In (SELECT ID
FROM TBL_SystemParameter
WHERE code = 'SOUND_WRONG_GARMENT')
if there are multiple ID's with that code OR use
UPDATE TBL_SystemParameter
SET [Value] = 'Ping.wav'
WHERE code = 'SOUND_WRONG_GARMENT'
either way and lose the IF statement as #Mureinik said.
Although Mureinik's answer is the logical solution to this, I will answer why this isn't actually working. Your condition is wrong, and this approach will work instead using IF EXISTS:
IF EXISTS (SELECT * FROM TBL_SystemParameter WHERE code='SOUND_WRONG_GARMENT')
BEGIN
UPDATE TBL_SystemParameter
SET [Value] = 'Ping.wav'
WHERE ID IN (SELECT ID
FROM TBL_SystemParameter
WHERE code = 'SOUND_WRONG_GARMENT')
END
As a side note, you're using an = sign instead of IN, which means you'll be matching to an arbitrary singular ID and only update 1 row based on this. To use a set based operation, use the IN clause.
You could actually 'golf' this by doing away with the derived query altogether, and using a simple WHERE code='SOUND_WRONG_GARMENT' on the table you're updating on.

Update multiple rows using one query

Can I update multiple rows using one query?
How to union following queries:
UPDATE tablename SET col1='34355' WHERE id='2'
UPDATE tablename SET col1='152242' WHERE id='44'
You can use a virtual map table for this update.
update tablename
inner join (
select '34355' col1, '2' id union all
select '152242' col1, '44' id
) map on map.id = tablename.id
set tablename.col1 = map.col1
Using this pattern allows for easy expansion (just add rows to the map). It also allows MySQL to more predictably choose an index on tablename.id for the normal JOIN operation.
Can you? Sure. Should you? No way.
Think about the person looking at your code in five years. What's more readable, this:
UPDATE tablename SET col1='34355' WHERE id='2';
UPDATE tablename SET col1='152242' WHERE id='44';
or this (The Scrum Meister's answer):
UPDATE tablename SET col1 = IF(id='2', '34355','152242') WHERE id='2' OR id='44';
The second one is shorter, but it's a challenge to figure out exactly what it's doing. If you're worried about race conditions, make it a single transaction (in most modern DBMS):
BEGIN;
UPDATE tablename SET col1='34355' WHERE id='2';
UPDATE tablename SET col1='152242' WHERE id='44';
COMMIT;
That way you can be guaranteed no other query will run when row 2 is updated but row 44 is not.
You can use a OR clause combined with the IF() function (or CASE WHEN... for other RDBMS)
UPDATE tablename SET col1 = IF(id='2', '34355','152242')
WHERE id='2' OR id='44'
Generally the only way you can update multiple rows in a single query is if your where clause matches multiple rows... and then every row will have the same values set.
Past that you can do funky stuff with expressions in your set clauses, but generally it's cleaner to do multiple queries, unless there's a very specific reason you can't.

SQL How do i update like this?

I'm trying to update all SQL rows in the [Temp_LTGData] table setting the [CORP_REG_NO] value to the value in another row in the same table where the [CUSTOMER_NUMBER] matches.
Ultimately I need to do this with quite a few columns, does anyone know if this can be done?
I can't seem to use the LTGSource alias like in a select query :(
Update [MandS].[dbo].[Temp_LTGData] LTGSource
Set [CORP_REG_NO] = (SELECT [CORP_REG_NO]
FROM [MandS].[dbo].[Temp_LTGData]
WHERE ([CORP_REG_NO] IS NULL
AND [CUSTOMER_NUMBER] = LTGSource.[CUSTOMER_NUMBER] ))
where [CORP_REG_NO] IS NULL
Thanks for the feedback guys that's some really awesome stuff, I even learnt some different approaches to this problem (voted for you all).
Try the following to get exactly what you were doing
UDPATE [MandS].[dbo].[Temp_LTGData] LTGSource
SET [CORP_REG_NO] = (SELECT [CORP_REG_NO]
FROM [MandS].[dbo].[Temp_LTGData]
WHERE ([CORP_REG_NO] IS NULL
AND [CUSTOMER_NUMBER] = ToUpdate.[CUSTOMER_NUMBER] ))
FROM {MandS].[dbo].[Temp_LTGData] ToUpdate
where [CORP_REG_NO] IS NULL
However, you have a mistake in your query I believe the subquery should be IS NOT NULL.
Something like this which will allow you to deal with many columns with a source and target row
If you need to link different rows for different columns, then it's more complex
If I understand correctly, filtering to CORP_REG_NO IS NULL would only work for CORP_REG_NO of course so you don't want to filter except to restrict target and source rows independently of specific column filters as per you're question.
Update
target
Set
[CORP_REG_NO] = CASE WHEN target.[CORP_REG_NO] IS NULL THEN source.[CORP_REG_NO] ELSE target.[CORP_REG_NO] END,
...and again...
FROM
[MandS].[dbo].[Temp_LTGData] target
JOIN
[MandS].[dbo].[Temp_LTGData] source ON target.[CUSTOMER_NUMBER] = source.[CUSTOMER_NUMBER]
WHERE
a filter to restrict rows perhaps
Try this:
UPDATE Temp_LTGData LTGSource
SET Col1 = L2.Col1, Col2 = L2.Col2, Col3 = L2.Col3
FROM LTGSource L1
JOIN LTGSource L2 ON L2.CORP_REG_NO IS NOT NULL AND L1.CUSTOMER_NUMBER = L2.CUSTOMER_NUMBER
WHERE L1.CORP_REG_NO IS NULL
That should do it for you. You're joining the updateable table to itself so you can have access to both the old row and the new row for the update. This way, you can update multiple columns at once.

Updating a table within a select statement

Is there any way to update a table within the select_expr part of a mysql select query. Here is an example of what I am trying to achieve:
SELECT id, name, (UPDATE tbl2 SET currname = tbl.name WHERE tbl2.id = tbl.id) FROM tbl;
This gives me an error in mysql, but I dont see why this shouldn't be possible as long as I am not changing tbl.
Edit:
I will clarify why I cant use an ordinary construct for this.
Here is the more complex example of the problem which I am working on:
SELECT id, (SELECT #var = col1 FROM tbl2), #var := #var+1,
(UPDATE tbl2 SET col1 = #var) FROM tbl WHERE ...
So I am basically in a situation where I am incrementing a variable during the select statement and want to reflect this change as I am selecting the rows as I am using the value of this variable during the execution. The example given here can probably be implemented with other means, but the real example, which I wont post here due to there being too much unnecessary code, needs this functionality.
If your goal is to update tbl2 every time you query tbl1, then the best way to do that is to create a stored procedure to do it and wrap it in a transaction, possibly changing isolation levels if atomicity is needed.
You can't nest updates in selects.
What results do you want? The results of the select, or of the update.
If you want to update based on the results of a query you can do it like this:
update table1 set value1 = x.value1 from (select value1, id from table2 where value1 = something) as x where id = x.id
START TRANSACTION;
-- Let's get the current value
SELECT value FROM counters WHERE id = 1 FOR UPDATE;
-- Increment the counter
UPDATE counters SET value = value + 1 WHERE id = 1;
COMMIT;