SQL Server Copy Random data from one table to another

早过忘川 提交于 2019-12-25 12:54:13

问题


I have 2 tables stuff and nonsense. nonsense is not the same size as stuff; in this case it is has fewer rows, but it may have more.

The structures are something like this:

CREATE TABLE stuff (
    id INT PRIMARY KEY,
    details VARCHAR(MAX),
    data VARCHAR(MAX)
);

CREATE TABLE nonsense (
    id INT PRIMARY KEY,
    data VARCHAR(MAX)
);

The stuff table is already populated with details, but data is NULL for now.

I would like to copy data from one row of nonsense at random into each row of stuff. Since nonsense is smaller, there will naturally be duplicates, which is OK.

This does not work:

UPDATE stuff
SET data=(SELECT TOP 1 data FROM nonsense ORDER BY NewId());

Presumably the sub query is evaluated once before the rest of the query. However that’s the sort of result I would have liked.

How do I achive this?


回答1:


You need to correlate the sub-query to run it for each record.

UPDATE stuff
SET data=(SELECT TOP 1 data 
          FROM nonsense 
          where stuff.id = stuff.id  --here
          ORDER BY NewId());


来源:https://stackoverflow.com/questions/45385261/sql-server-copy-random-data-from-one-table-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!