SQL Server Update Case When Then statment - sql-server-2008

I need to update a column [Recipient on contract] in the table [Check_Result]. But the value to insert into the column is not a fixed string but a value from [All_Contracts] table. Thus, all rows to inset into [Recipient on contract] are unique and can be found with the keys [ID Contract] = [Référence]
The link between tables [Check_Result] and [All_Contracts] is [ID Contract] = [Référence]
Update [Check_Result]
set [Recipient on contract] =
If [Bénéficiaire] ="Personne morale" Then
If [Organisme] is not null Then get [Organisme]
Else get [Professionnel de santé]
Else
If [Professionnel de santé] is not null Then get [Professionnel de santé]
Else get [Organisme]
Is It possible to use THEN in such situation? with a Update Case when then (select from inner join where) statement?
Thank you

Yes, each of the values in CASE statement can be replaced with nested select statement surrounded with '(' and ')', i.e. this is a valid statement:
update table1 set
field1 = CASE WHEN field2 = 'some value'
THEN (select field1 from table2 where table1.key_field = table2.key_field)
ELSE 'some default value'
END
You can do the same with IIF statement too
update table1 set
field1 = IIF(field2 = 'some value',
(select field1 from table2 where table1.key_field = table2.key_field),
'some default value')
Your update statement isn't quite clear. Which value you want to get from [All_Contracts] table? It can simplified like this:
Update [Check_Result] set
[Recipient on contract] = IIF([Bénéficiaire] = "Personne morale",
COALESCE([Organisme], [Professionnel de santé]),
COALESCE([Professionnel de santé], [Organisme]))
There you can replace [Professionnel de santé] or [Organisme] with (select SomeField from [All_Contracts] where [All_Contracts].[ID Contract] = [Check_Result].[Référence]).

Related

On DUPLICATE KEY, Conditional statement error ambiguous

INSERT INTO tb1 (title,Family,Complexity)
Select o.title,o.Family,o.Complexity from tb2 o
ON DUPLICATE KEY UPDATE
title = CASE WHEN title <> o.title THEN o.title ELSE title END,
Family = CASE WHEN Family <> o.Family THEN o.Family ELSE Family END,
Complexity = CASE WHEN Complexity <> o.Complexity THEN o.Complexity ELSE Complexity END ;
I am trying to update tb1 with the records in tb2, ONLY if the records do not match up, as I am using an after update trigger in another table.
However when trying to execute this, I get an error "Column 'title' in field list is ambiguous".
I have been unable to solve this. Please assist
Try with full table name
INSERT INTO tb1 (title,Family,Complexity)
Select o.title,o.Family,o.Complexity from tb2 o
ON DUPLICATE KEY UPDATE
tb1.title = CASE WHEN tb1.title <> o.title THEN o.title ELSE tb1.title END,
tb1.Family = CASE WHEN tb1.Family <> o.Family THEN o.Family ELSE tb1.Family END,
tb1.Complexity = CASE WHEN tb1.Complexity <> o.Complexity THEN o.Complexity ELSE tb1.Complexity END ;
This is because the title field exists in multiple tables/references.
You should prefix your title with the table name or it's reference.

Replace value in SQL Table

I like to replace a 'NULL' value in FG_NFG_Selektion column but only in those row where Plant='935S'
Tried:
UPDATE [Table] SET [FG_NFG_Selektion] = REPLACE([FG_NFG_Selektion], 'NULL', 'FG') WHERE [Plant] = '935S'
Message back: 10000 rows affected but still the same 'NULL' is there in the table.
Try with following query
UPDATE [Table] SET `FG_NFG_Selektion` = 'FG' WHERE `Plant` = '935S' AND `FG_NFG_Selektion` IS NULL;

UPDATE multiple rows with different values in one query in MySQL

I am trying to understand how to UPDATE multiple rows with different values and I just don't get it. The solution is everywhere but to me it looks difficult to understand.
For instance, three updates into 1 query:
UPDATE table_users
SET cod_user = '622057'
, date = '12082014'
WHERE user_rol = 'student'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '2913659'
, date = '12082014'
WHERE user_rol = 'assistant'
AND cod_office = '17389551';
UPDATE table_users
SET cod_user = '6160230'
, date = '12082014'
WHERE user_rol = 'admin'
AND cod_office = '17389551';
I read an example, but I really don't understand how to make the query. i.e:
UPDATE table_to_update
SET cod_user= IF(cod_office = '17389551','622057','2913659','6160230')
,date = IF(cod_office = '17389551','12082014')
WHERE ?? IN (??) ;
I'm not entirely clear how to do the query if there are multiple condition in the WHERE and in the IF condition..any ideas?
You can do it this way:
UPDATE table_users
SET cod_user = (case when user_role = 'student' then '622057'
when user_role = 'assistant' then '2913659'
when user_role = 'admin' then '6160230'
end),
date = '12082014'
WHERE user_role in ('student', 'assistant', 'admin') AND
cod_office = '17389551';
I don't understand your date format. Dates should be stored in the database using native date and time types.
MySQL allows a more readable way to combine multiple updates into a single query. This seems to better fit the scenario you describe, is much easier to read, and avoids those difficult-to-untangle multiple conditions.
INSERT INTO table_users (cod_user, date, user_rol, cod_office)
VALUES
('622057', '12082014', 'student', '17389551'),
('2913659', '12082014', 'assistant','17389551'),
('6160230', '12082014', 'admin', '17389551')
ON DUPLICATE KEY UPDATE
cod_user=VALUES(cod_user), date=VALUES(date)
This assumes that the user_rol, cod_office combination is a primary key. If only one of these is the primary key, then add the other field to the UPDATE list.
If neither of them is a primary key (that seems unlikely) then this approach will always create new records - probably not what is wanted.
However, this approach makes prepared statements easier to build and more concise.
UPDATE table_name
SET cod_user =
CASE
WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END, date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
You can use a CASE statement to handle multiple if/then scenarios:
UPDATE table_to_update
SET cod_user= CASE WHEN user_rol = 'student' THEN '622057'
WHEN user_rol = 'assistant' THEN '2913659'
WHEN user_rol = 'admin' THEN '6160230'
END
,date = '12082014'
WHERE user_rol IN ('student','assistant','admin')
AND cod_office = '17389551';
To Extend on #Trevedhek answer,
In case the update has to be done with non-unique keys, 4 queries will be need
NOTE: This is not transaction-safe
This can be done using a temp table.
Step 1: Create a temp table keys and the columns you want to update
CREATE TEMPORARY TABLE temp_table_users
(
cod_user varchar(50)
, date varchar(50)
, user_rol varchar(50)
, cod_office varchar(50)
) ENGINE=MEMORY
Step 2: Insert the values into the temp table
Step 3: Update the original table
UPDATE table_users t1
JOIN temp_table_users tt1 using(user_rol,cod_office)
SET
t1.cod_office = tt1.cod_office
t1.date = tt1.date
Step 4: Drop the temp table
In php, you use multi_query method of mysqli instance.
$sql = "SELECT COUNT(*) AS _num FROM test;
INSERT INTO test(id) VALUES (1);
SELECT COUNT(*) AS _num FROM test; ";
$mysqli->multi_query($sql);
comparing result to transaction, insert, case methods in update 30,000 raw.
Transaction: 5.5194580554962
Insert: 0.20669293403625
Case: 16.474853992462
Multi: 0.0412278175354
As you can see, multiple statements query is more efficient than the highest answer.
Just in case if you get error message like this:
PHP Warning: Error while sending SET_OPTION packet
You may need to increase the max_allowed_packet in mysql config file.
UPDATE Table1 SET col1= col2 FROM (SELECT col2, col3 FROM Table2) as newTbl WHERE col4= col3
Here col4 & col1 are in Table1. col2 & col3 are in Table2 I Am trying to update each col1 where col4 = col3 different value for each row
I did it this way:
<update id="updateSettings" parameterType="PushSettings">
<foreach collection="settings" item="setting">
UPDATE push_setting SET status = #{setting.status}
WHERE type = #{setting.type} AND user_id = #{userId};
</foreach>
</update>
where PushSettings is
public class PushSettings {
private List<PushSetting> settings;
private String userId;
}
it works fine

UPDATE query for multiple rows of same column

I have a database table and What I required to do is that,
I need to update the column with the column name 'Co15' of every rows according to the following conditions
Co15 = SAMPLE if Co13 = 'c1' AND Col2 = 'b4'
Co15 = LIST if Co13 = 'c6'
Currently I am running each update query separately as follows
UPDATE tblname SET Co15 = 'SAMPLE' WHERE Co13 = 'c1' AND Col2 = 'b4';
UPDATE tblname SET Co15 = 'LIST' WHERE Co13 = 'c6';
But wanted to know if there is any way where I could run only one update query all at once.
Thanks
Try this
UPDATE tblname SET Co15=
CASE
WHEN Co13 = 'c1' AND Col2='b4' THEN 'SAMPLE'
WHEN Co13 = 'c6' THEN 'LIST'
END
exactly getting the output to as following as:
UPDATE tblname
SET col5= CASE
WHEN col3 = 'c1' AND col2 = 'b4' THEN 'SAMPL'
WHEN col3 = 'c6' THEN 'LIST'
END
example: sqlfiddle to click here

Cancel Insert if inner query find nothing

I got the following query :
INSERT INTO contracts_settings (contract_id, setting_id, setting_value)
VALUES (:contract_id, (
SELECT setting_id
FROM settings
WHERE setting_type = :setting_type
AND setting_name = :setting_name
LIMIT 1
), :setting_value)
ON DUPLICATE KEY UPDATE setting_value = :setting_value
The value with the prefix : is replaced with data using PHP PDO::bindBalue.
If the inner query find nothing (it return NULL) but also INSERT a NULL statement. How to avoid that ?
Thanks.
Convert the INSERT ... VALUES syntax to INSERT ... SELECT:
INSERT INTO contracts_settings
(contract_id, setting_id, setting_value)
SELECT
:contract_id,
setting_id,
:setting_value
FROM settings
WHERE setting_type = :setting_type
AND setting_name = :setting_name
LIMIT 1
ON DUPLICATE KEY UPDATE
setting_value = :setting_value ;