SQL UPDATE SET =子查询集(随机)

时间:2013-07-12 16:35:44

标签: sql sql-server

我需要以下(这是伪代码):

UPDATE Cars SET Engine = (SELECT EngineName FROM Engines WHERE Type = 3)[RANDOMIZE_INDEX_FROM_1_TO_SUBQUERY_COUNT]

所以我基本上需要update所有Cars table来自子查询的随机引擎。这可能在MSSQL吗?

1 个答案:

答案 0 :(得分:2)

您可以使用公用表表达式为您的引擎查询行号,然后选择随机行号。

假设您有100个引擎 - 查询将如下所示:

;with CTE as (
   SELECT EngineName, ROW_NUMBER() over(order by EngineName) as rn
   FROM Engines WHERE Type = 3
)
UPDATE Cars SET Engine = (SELECT EngineName FROM CTE WHERE where rn = 1+CAST(rand()*100 as int))

更新:任何引擎计数

;with CTE as (
   SELECT EngineName, ROW_NUMBER() over(order by EngineName) as rn
   FROM Engines WHERE Type = 3
)
UPDATE Cars SET Engine = (SELECT EngineName FROM CTE WHERE where rn = 1+CAST(rand()*(SELECT COUNT(1) FROM CTE) as int))

更新2:多次更新(假设汽车表有ID字段或您可以排序的任何其他字段)

;WITH CTE_CARS AS (SELECT ENGINE, ROW_NUMBER() OVER (ORDER BY ID) AS RN FROM CARS)
,CTE_ENGINES AS (SELECT EngineName, ROW_NUMBER() OVER (ORDER BY NEWID()) AS RN FROM Engines WHERE Type = 3)
UPDATE CTE_CARS SET CTE_CARS.ENGINE = CTE_ENGINES.EngineName
FROM CTE_CARS JOIN CTE_ENGINES ON CTE_CARS.RN = CTE_ENGINES.RN

更新3:如果汽车数量多于发动机,则用

替换最后一个发动机
FROM CTE_CARS JOIN CTE_ENGINES ON (CTE_CARS.RN - CTE_ENGINES.RN) % (SELECT COUNT(1) FROM CTE_ENGINES) = 0