鉴于下表:
subscriber(id_sub, name_sub)
1 'Helen S.'
2 'Marie S.'
name_sub 列记录必须按顺序更新,并从表中随机获取值:
targeted_subscriber(id, target_name)
1 'Damien B'
我的意图是在UPDATE语句中使用JOIN子句。此外,获取随机 id 值。
对于这种情况,是否有优雅,直接的解决方案?
答案 0 :(得分:0)
如果我理解你的"随机取值",我认为你的意思是动态的?
如果是这样,那么我将使用join子句,类似于以下内容:
update subscriber
set name_sub = t.target_name
from subscriber s
join targeted_subscriber ts
on s.id_sub = ts.id
答案 1 :(得分:0)
使用Cursor
更新每行中的随机数据。不确定这是否是更好的做法
DECLARE @id_sub INT,
@name_sub VARCHAR(100)
DECLARE cur CURSOR FOR
SELECT id_sub,
name_sub
FROM subscriber
OPEN vendor_cursor
FETCH NEXT FROM cur INTO @id_sub, @name_sub
WHILE @@FETCH_STATUS = 0
BEGIN
UPDATE subscriber
SET name_sub = (SELECT TOP 1 target_name
FROM targeted_subscriber
ORDER BY Newid())
WHERE id_sub = @id_sub
FETCH NEXT FROM cur INTO @id_sub, @name_sub
END
CLOSE cur;
DEALLOCATE cur
答案 2 :(得分:0)
我会留给你让它适应更新
select getRand.sID, getRand.value
from ( select docSVsys.sID, docEnum1.value,
ROW_NUMBER() over (partition by docSVsys.sID order by docEnum1.eRand) as rownum
from ( select newid() sysRand, docSVsys.sID
from docSVsys
where docSVsys.sID < 100 ) docSVsys
join ( select newid() eRand, value
from docEnum1
where value is not null
and value <> 'null' ) docEnum1
on docSVsys.sysRand <= docEnum1.eRand ) getRand
where getRand.rownum = 1