我对此程序的表现有疑问。我在8 GB的i7上使用MS SQL SERVER 2012 Standard和SSMS。操作系统是Windows Server 2008。 我编写的过程能够在两个时间和日期之间的SQL表中插入或更新值。 例如
对于此过程,重要参数为
@startdate @Starttime
和@enddate @endtime
例如01.01.2014 00:00 - 01.12.2014 23:45 / 11
月。 SQL表中的输入每15分钟是非常必要的。
4 * 24 * 30 * 11 = 31580 11个月的值。这需要一些时间。
超过 6分钟!
如果我执行程序,则使用操作系统中的所有线程。
如何让我的慢速程序更智能,更快速?
USE [DB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[Insert_Into]
-- parameters for the stored procedure
@id int,
@StartDate date,
@EndDate date,
@Starttime time,
@Endtime time,
@value int
AS
DECLARE @TempTime time = @Starttime
BEGIN
SET NOCOUNT ON;
WHILE @Startdate <= @EndDate
BEGIN
WHILE @Starttime <= @Endtime
BEGIN
--If the entry exisits than update, if not, than insert
if exists (select date,ID from [dbo].[Insert_Table] where Datum = @StartDate + cast(@Starttime as datetime) AND ID = @id)
begin
PRINT @Starttime
UPDATE [dbo].[Insert_Table]
SET [ID] = @id, [datum] =( @StartDate + cast(@Starttime as datetime)), [value] = @value
WHERE ID = @id AND Datum =( @StartDate+ cast(@Starttime as datetime))
IF( @Starttime = @Endtime)
begin
print'EndDay'
SET @Starttime = DATEADD(Minute,1,@Endtime) -- Starttime One Minute over Endtime
end
else
select @Starttime = DATEADD(MINUTE,15,@Starttime)
end
else
begin
INSERT INTO [dbo].[Insert_Table]([ID],[date],[value])
VALUES
(@id, @StartDate + cast(@Starttime as datetime), @value )
IF( @Starttime = @Endtime)
begin
--print'EndDay'
SET @Starttime = DATEADD(Minute,1,@Endtime) -- Starttime one minute over Endtime
end
else
Select @Starttime = DATEADD(MINUTE,15,@Starttime)
end
END
--PRINT 'END'
SET @Starttime = @Temptime
Select @StartDate = DATEADD(DAY,1,@StartDate)
END
END
答案 0 :(得分:0)
使用CTE,在其上执行UNION ALL,这将创建一个比循环更好的草书循环。看这里Using CTE as a block loop ?
答案 1 :(得分:0)
非常感谢!太好了,这就是我要找的东西!
我的CTE新代码
USE DB
declare @StDate datetime = '01/01/2013 00:00.000'
declare @Enddate datetime = '01/06/2014 23:45.000'
declare @value as int = 400
declare @id as int = 999
;with cte as
(
select DATEADD(MONTH,DATEDIFF(MONTH,0,@StDate),0) as Sdate
union all
select DATEADD(MINUTE,15,SDate) from cte where SDate < @Enddate
)
Insert into Insert_Table(Date,Value,id)(select SDate as Date, @value,@id from cte )
OPTION (maxrecursion 0)
Select * from Insert_Table order by Date ASC