(This is a follow-up to the answer by “onedaywhen” on a question I posted earlier today.)
Hi everyone. Say I have a table MyTable with two int fields, PrimaryKey and MyNumber. (And other fields not directly relevant to this question). MyNumber has a unique constraint and a check constraint limiting it to BETWEEN 1 AND n. (Let’s say n=5 for now.)
1,2
2,NULL
3,5
4,NULL
5,NULL
6,1
7,NULL
How could an UPDATE be written to change the record where PrimaryKey=2 so that MyNumber has a non-NULL value? I don’t care what value it has, so long as it’s not a NULL and meets it’s two constraints of being unique and within range.
I’m using MS SQL Server, but I’m hoping there’s an answer using standard SQL.
(I’m also hoping there won’t have to be a table with the numbers 1 to n as contents.)
Many thanks.
In plain English:
WITH CTE AS ...).SELECT TOP 1 ...).UPDATE ...).If this query fails to find a suitable value, it will simply set the MyNumber to NULL.
WARNING: This might still viloate UNIQUE constraint on MyNumber in a concurrent environment (i.e. when two concurrently-executing transactions try to run this same query in parallel). So, you’d have to be prepared to retry the query if necessary.