我找到了一些解決方案,用#test2.src中的資料替換(如下例)#test.col2。但是在結果中,它只是選擇了一個單一的隨機值并將其全部替換。如何解決?謝謝!
#test(目標表)
col1 col2
-------------
A 1
B2
C 3
D 4 4
E 5
#test2(源表)
src1
sample1
樣本2
樣本3
查詢:
UPDATE #test
SET col1 = data1.LastName
FROM #test
CROSS APPLY
(SELECT TOP(1) #test2.LastName
FROM #test2.
ORDER BY NEWID()) data1
示例結果:
col1 col2
----------------
A樣本2
B樣本2
C樣本2
D樣本2
E樣本2
uj5u.com熱心網友回復:
這里有一個方法來解決這個問題。它是在一個cte中使用ROW_NUMBER來 "隨機化 "數值。
if OBJECT_ID('tempdb..#test') is not null
drop table #test;
創建 表 #test
(
col1 varchar(20)
, col2 int intinsert #test
select 'A', 1 union all #test
select 'B'/span>, 2 union all
select 'C , 3 union all
select 'D',4 union all
select 'E', 5;
如果OBJECT_ID('tempdb...#test2') 是 不是 nulldrop table #test2;
創建 表 #test2
(
LastName varchar(20)
);
insert #test2
select 'src1' union all
select 'sample1' union all
select 's sample2' union all
select 's sample3';
--這里是任何更新前的資料。
select * from #test;
with t1 as
(
select col1
, col2
, RowNum = ROW_NUMBER() over(order by newid() )
from #test
)
,t2 as
(
select LastName
, RowNum = ROW_NUMBER() over(order by newid()
from #test2
)
update t
set col1 = t2.LastName
from t1
join t2 on t1.RowNum = t2.RowNum
join #test t on t.col1 = t1.col1
--我們現在已經更新了一個 "隨機 "行。
select * from #test;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/307256.html
標籤:
上一篇:為什么Microsoft.SqlServer.Management.SqlParser.Parser為該查詢創建的AST包含SqlTableValuedFunctionRefExpression?
