我需要以下(这是伪代码):
UPDATE Cars SET Engine = (SELECT EngineName FROM Engines WHERE Type = 3)[RANDOMIZE_INDEX_FROM_1_TO_SUBQUERY_COUNT]
所以我基本上需要update
所有Cars table
来自子查询的随机引擎。这可能在MSSQL
吗?
答案 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