我有这样的桌子:
+-----------+--------------------------------------+--------------+
| DesignKey | DesignTypeGuid | DesignNumber |
+-----------+--------------------------------------+--------------+
| 2312 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 3 |
| 2313 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 7 |
| 2314 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 8 |
+-----------+--------------------------------------+--------------+
所以我通过查询获得DesignNumber
值:
DECLARE @CurrentChangeOrderDesignNumber INT =
(SELECT [DesignKey], [DesignNumber]
FROM [Design]
WHERE ParentDesignKey = @DesignKey
AND DesignTypeGuid = @COTypeGuid ORDER BY DesignKey);
我要做的是获取此数据并设置从1开始的新DesignNumber
值,所以我的期望结果应该是:
+-----------+--------------------------------------+--------------+
| DesignKey | DesignTypeGuid | DesignNumber |
+-----------+--------------------------------------+--------------+
| 2312 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 1 |
| 2313 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 2 |
| 2314 | 4FB560B0-E867-46B2-B116-338AD48C97AC | 3 |
+-----------+--------------------------------------+--------------+
我该如何实现?问候
答案 0 :(得分:3)
在SELECT
查询中,您将使用ROW_NUMBER()
:
SELECT [DesignKey], [DesignNumber],
ROW_NUMBER() OVER (PARTITION BY ParentDesignKey, DesignTypeGuid ORDER BY DesignNumber) as new_DesignNumber
FROM [Design]
WHERE ParentDesignKey = @DesignKey AND
DesignTypeGuid = @COTypeGuid
ORDER BY DesignKey;
如果要更新值,可以使用可更新的CTE:
WITH toupdate as (
SELECT d.*,
ROW_NUMBER() OVER (PARTITION BY ParentDesignKey, DesignTypeGuid ORDER BY DesignNumber) as new_DesignNumber
FROM Design d
WHERE ParentDesignKey = @DesignKey AND
DesignTypeGuid = @COTypeGuid
)
UPDATE toupdate
SET DesignNumber = new_DesignNumber;