我需要以下(这是伪代码):
UPDATE Cars SET Engine = (SELECT EngineName FROM Engines WHERE Type = 3)[RANDOMIZE_INDEX_FROM_1_TO_SUBQUERY_COUNT]
所以我基本上需要使用子查询update
中Cars table
的随机引擎。这可能吗?MSSQL
我需要以下(这是伪代码):
UPDATE Cars SET Engine = (SELECT EngineName FROM Engines WHERE Type = 3)[RANDOMIZE_INDEX_FROM_1_TO_SUBQUERY_COUNT]
所以我基本上需要使用子查询update
中Cars table
的随机引擎。这可能吗?MSSQL
您可以使用公用表表达式为引擎查询行号,然后选择一个随机行号。
假设您有 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:多行更新(假设 Cars 表有 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:对于 Cars 多于 enginges 的情况,将最后一个 FROM 替换为
FROM CTE_CARS JOIN CTE_ENGINES ON (CTE_CARS.RN - CTE_ENGINES.RN) % (SELECT COUNT(1) FROM CTE_ENGINES) = 0