Here's one option using a common table expression
and count() over partition
:
with cte as (
select *, count(*) over (partition by id1, id2) rn
from tblConnector
)
update cte
set id3 = 9999
where id3 = 1
and rn = 1;
سؤال
I have a table in SQL Server that contains rows, some of which I need to update, depending upon the absence/presence of other rows in the same table. the table and sample data look like this:
SQL Server table:
TABLE tblConnector(
ID1 [int] NOT NULL,
ID2 [int] NOT NULL,
ID3 [int] NOT NULL,
...other cols...)
It has a PRIMARY KEY CLUSTERED
on (ID1, ID2, ID3
) - meaning that the compound key must be unique.
Sample data:
ID1 ID2 ID3
-------------
111 222 1
111 222 9999
333 444 1 <--- update only this row
555 666 1
555 666 9999
777 888 2
777 888 9999
123 456 3 <--- don't update this row
I need to update any row in this table, setting ID3 = 9999
, where ID3
currently is 1 and there are no other rows in the table with the same values for ID1
and ID2
, with ID3 = 9999
.
In my sample data, I only want to update the 3rd row, setting ID3 = 9999
- because it has ID3 = 1
and there are no other rows in the table with the same ID1
and ID2
values (where ID3 <> 1
). I don't want to update the last row - so using count() to isolate rows isn't a valid approach.
I want to update the ID3 column to 9999 ONLY if the current value in ID3 is 1 ... AND there are no other rows that have the same ID1 and ID2 values where ID3 = 9999. ID1, ID2 and ID3 comprise a unique key and setting 9999 in ID3 can't duplicate a key value already in existence.
I've tried numerous attempts to join the table to itself, but I can't seem to get an UPDATE statement that will only affect the rows I want.
Any advice on how to code this SQL?
المحلول
Here's one option using a common table expression
and count() over partition
:
with cte as (
select *, count(*) over (partition by id1, id2) rn
from tblConnector
)
update cte
set id3 = 9999
where id3 = 1
and rn = 1;