update conditionally a field in case parameter is not null - sql

I need a query to update one field. If the passed parameter is null the do NOT update it with the null value of the parameter
update myTable
set myField1 = :param1
environment: hibernate and oracle

Can't you just put it in there where clause?
update myTable
set myField1 = :param1
where :param1 is not null
That'll avoid extra DML. Alternatively you can do:
update myTable
set myField1 = decode(:param1, null, myField1, :param)
But that means you'll update a field to the same, which isn't really optimal when you don't have to.

Related

Update all rows with one SQL query

I'm using this PostgreSQL table to store configuration variables:
CREATE TABLE SYS_PARAM(
SETTING_KEY TEXT NOT NULL,
VALUE_TYPE TEXT,
VALUE TEXT
)
;
How I can update all configuration settings values using one SQL statement?
you can use where true at the end and it update all rows in your table.
for example:
UPDATE table_name set table_column = value where true;
it will be update all rows in one SQL query.
If you plan on performing these updates more than once or twice over time, it would be good to have a function handle this for you. You could use the table itself as a type for a variadic parameter within a function, like so:
-- The function
CREATE OR REPLACE FUNCTION update_sys_param(VARIADIC params sys_param[])
RETURNS VOID
AS $$
BEGIN
UPDATE sys_param
SET value_type = upd.value_type, value = upd.value
FROM
sys_param src
INNER JOIN
UNNEST(params) upd
ON (src.setting_key = upd.setting_key);
END; $$ LANGUAGE PLPGSQL;
-- To call it
SELECT update_sys_param(('SMTP_PORT','int','123'),('SMTP_OTHER','text','435343'));
However, if this is a one-time update you can try either of these two:
UPDATE using JOIN
UPDATE sys_param
SET
value_type = new.value_type,
value = new.value
FROM
sys_param src
INNER JOIN
new_params new --< this table/view/cte must already exist or you must create it.
ON (src.setting_key = new.setting_key);
UPDATE using CASE
UPDATE sys_param
SET value = CASE setting_key
WHEN 'SMTP_PORT' THEN '2100'
(..and so on..)
END;
-- You would need to repeat the case statement if you intend on updating the value_type, too.
I guess you can achieve this by doing correlated update.
Please refer to the posts below:
https://www.ibm.com/support/knowledgecenter/ssw_i5_54/sqlp/rbafyexsub4.htm
You can join against a list of values and update with that:
update sys_param
set value = v.new_value
from (
values
('SMTP_PORT', '123'),
('SMTP_SERVER', 'new_server'),
('SMTP_USERNAME', 'Arthur')
) as v(skey, new_value)
where v.skey = sys_param.setting_key;
This assumes that setting_key is the primary key of that table.

How to insert a value into all cells under a column name

In my SQL table there is a column named IsApproved and it's all NULL. I want to turn them to 'TRUE'. I wrote this SQL statement but it didn't work :
INSERT INTO [persondb].[dbo].[Person] (IsApproved) VALUES ('True')
How can I make this work? Thanks.
update the table with the true value
update table [persondb].[dbo].[Person]
set IsApproved = 'True' where IsApproved is null
you need to update it not insert:
update [persondb].[dbo].[Person] set IsApproved ='True' -- or 1, depends on the field type
where IsApproved is null
Just try with this following one.
select IsNull(IsApproved,'true') from tablename.
(or)
update [persondb].[dbo].[Person] set IsApproved ='True' where IsApproved is null
Hope this will help you.
You can use ISNULL If you only want to show It as result (not to change in table) In following:
SELECT ISNULL(IsApproved, 'True')
If you want to change It in table you should use UPDATE.
UPDATE TABLE [persondb].[dbo].[Person]
SET IsApproved = 'True'
WHERE IsApproved IS NULL

Can I check if a variable is NULL within an Update's SET?

I have a stored procedure that uses a simple UPDATE with some variables passed to it. But I don't want to update those fields when their variables aren't null. This is essentially what my statement looks like.
UPDATE myTable
SET myColumn = #myColumn,
mColumn1 = #myColumn1
WHERE myColumn2 = #myColumn2
Is there anyway to apply some conditional logic within the SET? I have around 10 fields that need to be checked, so I wouldn't want to do an update per field or something like that.
Any ideas?
COALESCE is your friend. It returns its first non-NULL argument. I'm not actually sure from your narrative which way around you want things, it's either:
UPDATE myTable
SET myColumn = COALESCE(myColumn,#myColumn),
mColumn1 = COALESCE(myColumn1,#myColumn1)
WHERE myColumn2 = #myColumn2
Which keeps the current column's value if the column's not null, or
UPDATE myTable
SET myColumn = COALESCE(#myColumn,myColumn),
mColumn1 = COALESCE(#myColumn1,myColumn1)
WHERE myColumn2 = #myColumn2
Which keeps the current column's value if the variable is null.
Try to use coalesce function as below
UPDATE myTable
SET myColumn = coalesce(myColumn,#myColumn),
mColumn1 = coalesce(mColumn1,#myColumn1)
WHERE myColumn2 = #myColumn2
Above code updates your columns only when they are null. If they are not null the code sets the same value stored in the columns.
ISNULL ( variable , in case of null default value)
INFO

Append column's data to another column in SQL Server

I want to append everything in Field1 to Field2 and then make Field1 values NULL for all records in the table. I do not want to merge these fields into a single field, I still want both fields to remain.
Take the following example:
Field 1 Field 2
Test Value NULL
NULL Another Value
My Value Current Value
I want to end up with:
Field 1 Field 2
NULL Test Value
NULL Another Value
NULL Current ValueMyValue
Thanks in advance!
How about:
UPDATE table
SET Field2 = isnull(Field2,'') + isnull(Field1,''), Field1 = NULL
What I would suggest if you are not sure about it is to wrap the update in a BEGIN TRAN, ROLLBACK like so:
BEGIN TRAN
SELECT * FROM thistable
UPDATE thistable
SET Field2 = isnull(Field2,'') + isnull(Field1,'')
, Field1 = NULL
SELECT * FROM thistable
ROLLBACK
That way you will get a view of what the query will do before it makes the change 'permanent'. Once you are happy change ROLLBACK to COMMIT and run again.
VIEW DEMO HERE
How about:
UPDATE MyTable
SET Field2 = ISNULL(Field2, '') + ISNULL(Field1, '')
To join the values into Field2.
And
UPDATE MyTable
SET Field1 = NULL
To clear out Field1 once you are sure the first script worked.
How about a little something like this:
UPDATE <Table name> SET field_2 = CONCAT(field_2, field_1);
UPDATE <Table name> SET field_1 = NULL;

IF UPDATE() in SQL server trigger

If there's:
IF UPDATE (col1)
...in the SQL server trigger on a table, does it return true only if col1 has been changed or been updated?
I have a regular update query like
UPDATE table-name
SET col1 = 'x',
col2 = 'y'
WHERE id = 999
Now what my concern is if the "col1" was 'x' previously then again we updated it to 'x'
would IF UPDATE ("col1") trigger return True or not?
I am facing this problem as my save query is generic for all columns, but when I add this condition it returns True even if it's not changed...So I am concerned what to do in this case if I want to add condition like that?
It returns true if a column was updated. An update means that the query has SET the value of the column. Whether the previous value was the same as the new value is largely irelevant.
UPDATE table SET col = col
it's an update.
UPDATE table SET col = 99
when the col already had value 99 also it's an update.
Within the trigger, you have access to two internal tables that may help. The 'inserted' table includes the new version of each affected row, The 'deleted' table includes the original version of each row. You can compare the values in these tables to see if your field value was actually changed.
Here's a quick way to scan the rows to see if ANY column changed before deciding to run the contents of a trigger. This can be useful for example when you want to write a history record, but you don't want to do it if nothing really changed.
We use this all the time in ETL importing processes where we may re-import data but if nothing really changed in the source file we don't want to create a new history record.
CREATE TRIGGER [dbo].[TR_my_table_create_history]
ON [dbo].[my_table] FOR UPDATE AS
BEGIN
--
-- Insert the old data row if any column data changed
--
INSERT INTO [my_table_history]
SELECT d.*
FROM deleted d
INNER JOIN inserted i ON i.[id] = d.[id]
--
-- Use INTERSECT to see if anything REALLY changed
--
WHERE NOT EXISTS( SELECT i.* INTERSECT SELECT d.* )
END
Note that this particular trigger assumes that your source table (the one triggering the trigger) and the history table have identical column layouts.
What you do is check for different values in the inserted and deleted tables rather than use updated() (Don't forget to account for nulls). Or you could stop doing unneeded updates.
Trigger:
CREATE TRIGGER boo ON status2 FOR UPDATE AS
IF UPDATE (id)
BEGIN
SELECT 'DETECT';
END;
Usage:
UPDATE status2 SET name = 'K' WHERE name= 'T' --no action
UPDATE status2 SET name = 'T' ,id= 8 WHERE name= 'K' --detect
To shortcut the "No actual update" case, you need also check at the beginning whether your query affected any rows at all:
set nocount on; -- this must be the first statement!
if not exists (select 1 from inserted) and not exists (select 1 from deleted)
return;
SET NOCOUNT ON;
declare #countTemp int
select #countTemp = Count (*) from (
select City,PostCode,Street,CountryId,Address1 from Deleted
union
select City,PostCode,Street,CountryId,Address1 from Inserted
) tempTable
IF ( #countTemp > 1 )
Begin
-- Your Code goes Here
End
-- if any of these "City,PostCode,Street,CountryId,Address1" got updated then trigger
-- will work in " IF ( #countTemp > 1 ) " Code)
This worked for me
DECLARE #LongDescDirty bit = 0
Declare #old varchar(4000) = (SELECT LongDescription from deleted)
Declare #new varchar(4000) = (SELECT LongDescription from inserted)
if (#old <> #new)
BEGIN
SET #LongDescDirty = 1
END
Update table
Set LongDescUpdated = #LongDescUpdated
.....