强制sql server停止缓存子查询

时间:2016-08-23 12:33:31

标签: sql-server caching

我试图在数据库中插入虚拟数据用于测试目的,并匹配我需要根据另一个表的值更新一个表的所有id的关系。

我尝试执行的查询是

update LG set BatchID=(SELECT TOP 1 BatchID FROM Batch
ORDER BY NEWID())

但是LG的BatchID只填充了一个值似乎是内部查询的缓存结果,如何强制它不要对子查询进行缓存。

2 个答案:

答案 0 :(得分:1)

您可以使用MERGEROW_NUMBER()将表相关

;WITH LG_cte AS (
SELECT  *,
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn
FROM LG
), Batch_cte AS (
SELECT  *,
        ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn
FROM Batch
)

MERGE LG_cte as lg
USING Batch_cte as b
ON lg.rn = b.rn
WHEN MATCHED THEN   
    UPDATE SET BatchID = b.BatchID;

F.e。我拿到了这张桌子:

CREATE TABLE LG (
    BatchID int,
    SomeString nvarchar(max)
)
CREATE TABLE Batch (
    BatchID int,
    SomeString1 nvarchar(max)
)

INSERT INTO LG VALUES
(1,'a'),
(2,'b'),
(3,'c'),
(4,'d')

INSERT INTO Batch VALUES
(7,'e'),
(8,'f'),
(9,'g'),
(10,'h')

运行上面的合并后,我会得到:

BatchID SomeString
7       a
8       b
9       c
10      d

LG

答案 1 :(得分:0)

你可以这样使用

update table1 set id = (select newid())

如果有newid()的缓存,那么你可以使用rand()