到目前为止,我有这个:
UPDATE A
SET DefaultContact = 1
FROM [StatementsDB].[dbo].[tblSupplierContact] A
INNER JOIN (SELECT B.FK_SupplierID
FROM [StatementsDB].[dbo].[tblSupplierContact] B
INNER JOIN [StatementsDB].[dbo].[tblSupplier] C ON B.FK_SupplierID = C.SupplierID
WHERE C.FK_ClientID = 3
GROUP BY B.FK_SupplierID) D ON A.FK_SupplierID = D.FK_SupplierID
因此,将默认联系人设置为1,其中SupplierID
与tblSupplierContact
匹配,以加入SupplierID
。但是,我只需更新tblSupplierContact
中的一个重复记录,而不是每个记录。
示例如下:
FK_SupplierID Email DefaultContact
1 Email1 0
1 Email2 0
1 Email3 0
1 Email4 0
所以我想说我只想更新这些重复记录中的第一个。我到目前为止,我只是不知道如何做最后一部分。
答案 0 :(得分:2)
这是可更新CTE的一个很好的例子:
DECLARE @tblTest TABLE(FK_SupplierID INT,Email VARCHAR(100),DefaultContact BIT);
INSERT INTO @tblTest VALUES
(1,'Email1',0)
,(1,'Email2',0)
,(1,'Email3',0)
,(1,'Email4',0)
,(2,'Email1',0)
,(2,'Email2',0)
,(2,'Email3',0)
,(2,'Email4',0);
WITH Numbered AS
(
SELECT --choose an order by clause, if the choice should not be random...
ROW_NUMBER() OVER(PARTITION BY FK_SupplierID ORDER BY (SELECT NULL)) AS Nr
,*
FROM @tblTest
)
UPDATE Numbered SET DefaultContact = 1 WHERE Nr = 1;
SELECT * FROM @tblTest;