我尝试更新表格中的值,使其具有“&UNKNOWN'”格式的唯一值。 + 0001下一个将是“未知”' + 0002.我试图更新字段时遇到一些麻烦。
DECLARE @idtest VARCHAR(15)
SET @idtest = ''
UPDATE TABLE1
SET @idtest = ID = CONVERT(int,'UNKNOWN'+ CAST(@idtest + 1 AS VARCHAR(15)))
where ID is null or LTRIM(RTRIM(ID )) = ''
GO
任何建议都会很棒。我只能使用2008 R2之前支持的sql。
更新:
WITH tempUpdateTable AS (
SELECT t1.*,
ROW_NUMBER() over (ORDER BY (SELECT NULL)) AS seqnum
FROM table1 t1
WHERE ID IS NULL OR LTRIM(RTRIM(ID)) = ''
)
UPDATE tempUpdateTable
SET ID= 'UNKNOWN' + RIGHT('000' + CAST(seqnum AS VARCHAR(255)), 4);
答案 0 :(得分:3)
使用row_number()
和可更新的CTE:
with toupdate as (
select t1.*,
row_number() over (order by (select NULL)) as seqnum
from table1
where ID is null or ltrim(trim(ID )) = ''
)
update toupdate
set id = 'UNKNOWN' + right('00000000', cast(seqnum as varchar(255)), 8);
答案 1 :(得分:1)
你也可以这样做:
DECLARE @idtest INT
SET @idtest = 0
UPDATE TABLE1 WITH( TABLOCKX )
SET @idtest = @idtest + 1,
ID = 'UNKNOWN'+ RIGHT( '0000' + CAST(@idtest AS VARCHAR(15)) , 4 )
where ID is null or LTRIM(RTRIM(ID )) = ''
WITH( MAXDOP = 1 )
这与您所拥有的几乎相同,不同之处在于SQL Server不支持多个分配。
说明:
WITH( TABLOCKX )
- 表上的独占锁定,需要避免多次更新WITH( MAXDOP = 1 )
- 最大并行度设置为1.换句话说,SQL无法执行任何可能导致排序关闭的任务并行化。