Get last updated column from an update action in SQL Server - sql

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.

Related

How to Update a column Before Select?

I am setting a stored procedure for select and I want to update the value of one column in the database Before doing the Select.
This is what I tried but it's not working.
#roleID int and #query varchar(240)
SELECT
EP.Equipe_Projet_Id AS PROJET_ID,
U.USR_ID,
CleRepartition = CASE
WHEN #RoleID = 1 AND #query IS NOT NULL
THEN 100
AND (UPDATE EQUIPE_PROJET SET CleRepartition = 100
WHERE EP.Equipe_Projet_Id = #PROJET_ID AND EP.Role_Id = 3)
ELSE NULL
END
FROM
[EQUIPE_PROJET] EP
Expecting update of column on database and having it's value
i want to update the value of Column CleRepartition in the database while selecting.
This is not possible in a SELECT query. A SELECT retrieves data from the database. An UPDATE modifies data. These are two separate statements and cannot be combined.
You are doing this work in a stored procedure. Within a stored procedure, you can run an UPDATE and SELECT in any order, so you can accomplish both tasks. If you are concerned about data changing in the database between the two statements, you can wrap them in a transaction.
Stored procedure can do update then select after.
So I added the query of update in the beginning, then I do the select.
Like this:
UPDATE EP
SET CleRepartition = CASE
WHEN #RoleID = 1 AND #query IS NOT NULL
THEN 100
AND (UPDATE EQUIPE_PROJET
SET CleRepartition = 100
WHERE EP.Equipe_Projet_Id = #PROJET_ID
AND EP.Role_Id = 3)
ELSE NULL
END
FROM [EQUIPE_PROJET] EP
SELECT
EP.Equipe_Projet_Id AS PROJET_ID,
U.USR_ID,
CleRepartition
FROM
[EQUIPE_PROJET] EP
I hope that this will help someone.

Not able to update columns of a table by bind parameters using sql developer

The following select statement returns one row:
SELECT *
FROM CM_APOLLO_DET
WHERE
CM_APOLLO_DET.DETAIL_ID = TRIM(:detailId) AND
CM_APOLLO_DET.HEADER_ID IN (SELECT HEADER_ID FROM CM_APOLLO_HDR
WHERE TRIM(FILE_NAME) = TRIM(:fileName));
Values of bind parameters are as follows:
detailId: 775686609762
filename:sample3.txt
but when I run following update statement, it updates zero rows.
UPDATE CM_APOLLO_DET
SET CM_APOLLO_DET.DIVISION = :div
WHERE
CM_APOLLO_DET.DETAIL_ID = TRIM(:detailId) AND
CM_APOLLO_DET.HEADER_ID IN (SELECT HEADER_ID FROM CM_APOLLO_HDR
WHERE TRIM(FILE_NAME) = TRIM(:fileName));
div=2030
detailId: 775686609762
filename:sample3.txt
This update where condition is same as above select statement.
You can try below using exists
update CM_APOLLO_DET set CM_APOLLO_DET.DIVISION=:div
where CM_APOLLO_DET.DETAIL_ID=trim(:detailId) and
exists (SELECT 1 from
CM_APOLLO_HDR where CM_APOLLO_DET.HEADER_ID=CM_APOLLO_HDR.HEADER_ID
and trim(FILE_NAME)=trim(:fileName)
);

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

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)

Using Insert and Update statements in a related operation

I want to insert a record to a table called Payment which has column ID as the primary key(Auto Increment) and then I want to get that ID to use in a WHERE clause of another update statement.
var insertSatement = #"BEGIN INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount) VALUES(#type, #reference, #date, #totalRecords, #totalAmount ) ";
var updateStatement = #"UPDATE SalaryTrans SET payment_id = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id) WHERE SalaryTrans.id = #paramID ";
These two statements could not be merged as the update is going to update multiple rows. It will update all matching rows of the SalaryTrans table. So I'm using a foreach loop.
//open connection, add parameters
sqlCommand.CommandText = insertStatement;
sqlCommand.ExecuteNonQuery(); // This inserts...
foreach(PaymentInfo p in paymentList)
{
paramID.value = p.id;
sqlCommand.CommandText = updateStatement;
sqlCommand.ExecuteNonQuery();
}
In the loop each time "SELECT TOP 1 id..." is also executed. To avoid it, is there a way to use SCOPE_IDENTITY() to get the last updated ID from Payment table and use it in the loop?
Would there be a difference if I change update statement as follows in this context (performance wise) ?
DECLARE #ID INT = (SELECT TOP 1 id FROM Payment ORDER BY Payment.id)
UPDATE SalaryTrans SET payment_id = #ID WHERE SalaryTrans.id = 1
Or else should I separate this SELECT from the UPDATE to keep it outside the loop?
NOTE : My main concentration here is the performance factor.
What you can also try is, change your statement like below
var insertSatement = #"BEGIN INSERT INTO Payment (payment_type, reference, payment_date, total_records, total_amount) VALUES(#type, #reference, #date, #totalRecords, #totalAmount ); SELECT CAST(scope_identity() AS int) ";
Then in your excecute non query get the return value
sqlCommand.CommandText = insertStatement;
int id = (int) sqlCommand.ExecuteScalar(); // This inserts...
You can use the id in the loop
You can use SCOPE_IDENTITY
It will contain the latest value of the identity column from the newly inserted row
http://msdn.microsoft.com/en-us/library/ms190315.aspx

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