gpt4 book ai didi

sql - 使用 SQL 添加/更新批量数据

转载 作者:搜寻专家 更新时间:2023-10-30 23:39:19 25 4
gpt4 key购买 nike

我们正在使用 SQL Server Management Studio 将批量数据插入到我们的一个数据库表中。目前,我们处于发送到数据库的数据将被添加到表中特定行的位置(这由存储过程控制)。我们发现在操作完成之前发生了超时;在这一点上,我们认为由于 while 循环,操作很慢,但我们不确定如何编写更快的等价物。

-- Insert statements for procedure here
WHILE @i < @nonexistingTblCount
BEGIN
Insert into AlertRanking(MetricInstanceID,GreenThreshold,RedThreshold,AlertTypeID,MaxThreshold,MinThreshold)
VALUES ((select id from @nonexistingTbl order by id OFFSET @i ROWS FETCH NEXT 1 ROWS ONLY), @greenThreshold, @redThreshold, @alertTypeID, @maxThreshold, @minThreshold)

set @id = (SELECT ID FROM AlertRanking
WHERE MetricInstanceID = (select id from @nonexistingTbl order by id OFFSET @i ROWS FETCH NEXT 1 ROWS ONLY)
AND GreenThreshold = @greenThreshold
AND RedThreshold = @redThreshold
AND AlertTypeID = @alertTypeID);

set @i = @i + 1;
END

其中 @nonexistingTblCount 是表 @nonexistingTbl 中的总行数。 @nonexistingTbl 表较早声明,包含我们要添加到表中的所有值。

最佳答案

您应该能够用一条语句插入所有记录,而不是使用循环。

INSERT INTO AlertRanking(MetricInstanceID,GreenThreshold,RedThreshold,AlertTypeID,MaxThreshold,MinThreshold) 
SELECT id, @greenThreshold, @redThreshold, @alertTypeID, @maxThreshold, @minThreshold FROM @nonexistingTbl ORDER BY id

关于sql - 使用 SQL 添加/更新批量数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37009393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com