[英]I need to create a column with the number of times the same value is kept in the table. SQL Server
[英]SQL Server : problem updating a counter type column in a table. All rows get the same value and they should not
我是 SQL 的新手,正在寻求帮助,以使用计算值更新表列中的每条记录。 我确定我想多了!
我需要遍历所有记录 (870K+) 并增加一个计数器变量,其值介于 01 和 99(2 位数字)之间,这将替换我表中MemoKeyExtension
(NChar 2) 列中的值。
为简单起见,您可以假设此表只有一个uniqueid
列、一个account number
列 (int) 和MemoKeyExtension
(nChar2) 列。
DECLARE @COUNT as Int
SET @COUNT = 0
DECLARE Mem_Cursor CURSOR FOR
SELECT MemoKeyExtension FROM Customer.Memo
OPEN MEM_Cursor
FETCH NEXT FROM MEM_Cursor
WHILE @@FETCH_STATUS = 0
BEGIN
IF @COUNT < 99
BEGIN
SET @COUNT = @COUNT + 1
END
ELSE
BEGIN
SET @COUNT = 1
END
UPDATE Customer.Memo
SET MemoKeyExtension = REPLACE(STR(@COUNT,2),' ','0')
WHERE CURRENT OF MEM_Cursor
FETCH NEXT FROM MEM_Cursor
END
CLOSE MEM_Cursor
DEALLOCATE MEM_Cursor
Example of desired results:
MemoId MemoKeyExtension
F630A22A-6BAA-4F86-84FB-0823FCAD95A0 95
7BE0E85D-9CA8-4E01-888E-781D5356EDB8 96
5D7BD8F2-5858-4A8F-96B0-E93D44030925 97
9520A24A-5168-41E8-ADFF-429513EB3693 98
5890818B-6EBB-4CD4-94C6-D467679427E5 99
B730FD54-F231-494E-A7F0-E7162F2EDD10 01
578A2457-39DF-41A4-953C-4A3C9E69F394 02
F316C39C-6ACA-4A7C-A401-39518F2EF9A1 03
感谢您提供任何帮助。
由于我们没有可使用的表定义,所以这里主要是猜测。 如果这不起作用,它应该非常接近。
with MyNumbers as
(
select NewVal = right('0' + convert(varchar(2), ROW_NUMBER() over (order by (select null)) % 99), 2)
, MemoId
from Customer.Memo m
)
update m
set MemoKeyExtension = case when NewVal = '00' then '99' else n.NewVal end
from Customer.Memo m
join MyNumbers n on n.MemoId = m.MemoId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.