How does SQL Server handle an update with no change? - sql

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;

Related

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)

T-SQL - need to run update if only one record returned by query

I need to update a record IFF there is only one record matching my search criteria. Here's what I have, but it's crude:
DECLARE #TestCount INT;
SELECT #TestCount = COUNT(*)
FROM TestRecords tr
WHERE
tr.UnitSerial = #UnitSerial
AND
tr.PassFailStatus = 1;
IF (#TestCount = 1)
UPDATE
TestRecords
SET
Invalid = 1
WHERE
TestRecordID =
(SELECT TestRecordID
FROM TestRecords tr
WHERE
tr.UnitSerial = #UnitSerial
AND
tr.PassFailStatus = 1);
Of course this is example code - there are more restrictions and tables joins, etc in the SELECT statement, and it's all wrapped by a transaction, but this is the gist of the stored proc logic.
I'm thinking there has to be a better way but I don't know what that is. Any suggestions?
Thanks, Dave
You could do it in one query as:
with toupdate as (
select tr.*,
count(*) over () as cnt
from TestRecords tr
where tr.UnitSerial = #UnitSerial AND tr.PassFailStatus = 1
)
update toupdate
set Invalid = 1
where cnt = 1
This assumes you are using SQL 2005 or greater.
I think your code will run without problems!
Use ##ROWCOUNT variable to determine how many records was affected by a SELECTE, UPDATE, INSERT statement: but in your case you have just set your #TestCount variable with the same result!
It's not far off what I would do, which is simply:
IF (SELECT COUNT(*) FROM x WHERE y = z) = 1
BEGIN
--statements
END
Of course, you could replace the condition with anything, e.g. a UDF with more complex dynamic conditions.

SQL update query

I want to update two fields in one sql query. How do I do that?
update tablename set field1= val1 where id=1
Now I want to update 2 fields as follows: How can I do that?
update tablename set field1 =val1 and set field2=val2 where id=1
Your syntax is almost correct, but you can't use AND.
UPDATE tablename SET field1=var1, field2=var2 WHERE id=1
Or to be safe, I like to write UPDATE statements like this:
UPDATE T
SET
T.Field1 = Value1
,T.Field2 = Value2
-- SELECT *
FROM TableName AS T
WHERE T.ID = 1
This way you can be sure of what you'll be updating.
UPDATE TableName
SET Field1=Value1
,Field2=Value2
WHERE id=id_value
Like the others, but this is how I like to indent and format it, on bigger complex queries, proper formating matters alot!
You almost had it:
update tablename
set field1=val1,
field2=val2
where id=1
UPDATE tablename SET field1 = var1, field2 = var2 WHERE id = 1;
COMMIT;

Help Constructing an Oracle SQL with Condition

I need some help in creating an Oracle SQL which I will execute in .NET.
I need to update a column in a table but the value to update the same would be dependent on two different values. To give an example:
Dim sqlcmd as String
Dim collCmd as Collection
For x = 1 to intCount
sqlcmd = "Update tableA Set col1 = :val1, col2 = :val2 Where...."
collcmd.add(sqlcmd)
SELECT col1, col2
FROM tableA
Where .....
If col1 = 0 and col2 = 0 then
sqlcmd = "Update tableB
Set col1 = :value
Where...."
Else
sqlcmd = "Update tableB
Set col1 = :value
Where.."
End If
collcmd.add(sqlcmd)
Next
'Perform the update with transaction here for the collcmd collection.
Apparently, I need to place the update in one sql where the condition is met. Kindly advise. I cannot do a one time execute non query here since if one of the update fails, then I would need to perform a transaction rollback. I am placing all the update statement in one collection and performing the update in one transaction. But the value for the tableA may be different on the next iteration.
Kindly take note that I cannot place the same inside a stored proc since there are other sql commands which are executed prior to the statements above.
Is there a way to create an SQL where the update would go something like:
sqlcmd = "UPDATE tableB b
IF select a.col1 = 0 and select a.col2 = 0 from tableA a
SET b.col1 = "this value"
ELSE
SET b.col1 = "other value"
WHERE...."
Thanks.
You need to use the CASE expression, like so:
UPDATE tableB
SET col1 =
CASE WHEN (0, 0) = (SELECT col1, col2
FROM tableA
WHERE <tableA constraints>
)
THEN "this value"
ELSE "that value"
END
WHERE <tableB constraints>;
Note also the case is using the (a,b,c) = (select A, B, C ...) syntax, which is a handy, but underused sql feature = you can compare not only single values (scalars) but multiple values (vectors).
Why not write whatever logic you need in a stored procedure/package and call that from .NET?
The best thing to do this is with stored procedures. If you have other sql commands or what ever, then use transactions: run as stored procedures as you want intercalated with data that does not come from database, the commit (or rollback).
If something changes the stored procedures becomes invalid on text-sql does not happens, you have to wait to unit-tests o runtime error. We use generated code that makes very easy to call stored procedures (class.method).
DISCLAIMER: I'm not an stored procedure fanatic. I use Stored Procedures and ORM as best fits on each moment. It depends on the case.

if-else condition for update a table in a stored procedure in SQL Server 2005

I want to update some data in a specified case, else these columns are not to be updated.
What can I write code in a stored procedure for this?
You can use a case to control whether you assign a new value or keep the old value.
update <sometable>
set field = case when <condition> then <newvalue> else field end
where <condition>
Example:
update questions
set reply = case when #input is not null then #input else reply end
where answer = 42
Use Case statement in Update clause
like
SQL Statement #6
UPDATE titles
SET price =
CASE
WHEN (price < 5.0 AND ytd_sales > 999.99)
THEN price * 1.25
WHEN (price < 5.0 AND ytd_sales < 1000.00)
THEN price * 1.15
WHEN (price > 4.99 AND ytd_sales > 999.99)
THEN price * 1.2
ELSE price
END
Taken from SQL SERVER UPDATE
Also you can go with if..else statement
If you would have been in SQL SERVER 2008, you could have avail the flavor of MERGE statement
Just an example:
IF #a <= 0
BEGIN
UPDATE table SET counter = #a, name = 'Minati'
END
ELSE
BEGIN
UPDATE table SET name = 'Minati'
END
May be you can build the condition in the update command and easily run more than one update with the diferent conditions. It may not be the most elegant way but it is prety eficient. It depends of your needs.
UPDATE table SET field=value WHERE <<condition>>
UPDATE table SET field=value2 WHERE <<condition2>>