SQL Update if null add 1 otherwise add 1 to current value - sql

I have a query that is updating a field in my table. It could be the case that that column to be updated can be NULL if that's the case i'd like to add 1 to that cell. Otherwise i'd like to add 1 to the current value of that field.
UPDATE SET Scheduled = Scheduled + 1
Would work except when cell's have NULL as their value, it does not add the 1 value.

You can use this.
UPDATE table SET Scheduled = ISNULL(Scheduled,0) + 1

You could use CASE expression:
UPDATE table_name
SET Scheduled = CASE WHEN Scheduled IS NULL THEN 1
ELSE Scheduled + 1
END
WHERE ...;

Although you can easily do this in the update:
update t
set scheduled = coalesce(scheduled + 1, 1)
where . . .;
I would suggest removing the need for it, by defaulting the value to 0. I suspect that will make sense in your context. If you have data in the table:
update t
set scheduled = 0
where scheduled is null;
alter table t alter scheduled int not null default 0;
(Note: You can also use with values in the alter, but the update clearly shows the intent.)

Update yourTable set yourColumn=(coalesce(yourColumn,0)+1)
Or you can use
Update yourTable set yourColumn=(nullif(yourColumn,0)+1)

Related

Get last updated column from an update action in SQL Server

UPDATE sms.customerOtp
SET validateCounts = validateCounts + 1
WHERE customerID = '123'
After this update I need to run a select statement that should return the last updated value of validateCounts.
Is there any functions similar to SCOPE_IDENTITY to get the last updated value of a non-identity column?
You can use the OUTPUT clause:
UPDATE sms.customerOtp
OUTPUT validateCounts
SET validateCounts = validateCounts + 1
WHERE customerID = 123;
Normally, I would put the result into a table variable, but you can use it without a table variable.

How does SQL Server handle an update with no change?

I want to run an update statement using a case statement. 99% of time there will be no change. So I was wondering about the performance.
For example if I run
update <table>
set field1 = field1
does it copy field1 and then write it into field1 or does it do nothing?
That depends on the database and in SQL Server, the answer is yes.
You should filter the values instead. Instead of:
update t
set x = (case when a = b then c else x end);
You should do:
update t
set x = c
where a = b;

How to delete datetime value using update?

I have a row with datetime. What I want to achieve is delete the datetime in just a blank. Is that possible with using update? If possible I don't want to delete and re-insert the data because this is what I tried and it so inefficient.
Here is my table:
+++++++++++++++++++++++++++++++++++++
+ ID + Name + AppvlDt +
+++++++++++++++++++++++++++++++++++++
+ 1 + JB + 02/11/2019 00:00:00 +
+++++++++++++++++++++++++++++++++++++
I want to delete the AppvlDt into just a plain blank. Is that possible using Update?
You can certainly null out your datetime field, e.g.
UPDATE yourTable
SET AppvlDt = NULL
WHERE ID = 1;
Whether or not doing this actually makes sense depends on other things though.
Just run this DML script.
update table Set AppvlDt = ''

Loop for updating rows with a condition

I have 2 bit columns in a table active and suspended
The active column already contains values but the suspended column still null
How can I fill the suspended field with values that is opposite of active?
I was stuck in this code..
Declare #suspended bit;
--some conditions
Update Users_mock
Set Suspended = #Suspended;
A simple case statement should work:
Update userM
Set suspend = case active when 0 then 1 else 0 end
You may check this Update sql bit field in database.
It says, **Bits in SQL Server are always stored as 1 or 0 in a bitmap. **
You may use a where, if-else or case to update the column.
select abs(CONVERT(int,#suspended)-1)
Try this:
update Users_mock
set Suspended = case when active=1 THEN 0
else 1
end
Please try:
Update Users_mock
Set Suspended = 1-Active;

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
.....