我是SQL Server的新手,最后让我的代码运行,但速度非常慢。我的数据库有点偏大(1.22千米行,3列),我有一些while循环,我知道这是不理想但我无法找到解决方法。
任何帮助都将非常感谢!!!
declare @b float
declare @c float
declare @dateloopfora datetime
declare @dateloopforc datetime
BEGIN
SET @MYCURSOR = CURSOR FOR
SELECT DISTINCT [STOCKS] FROM [tsxvPrices].[dbo].[3coldata]
OPEN @MYCURSOR
FETCH NEXT FROM @MYCURSOR INTO @STOCK
set @end = '12/30/2012'
WHILE @@FETCH_STATUS = 0
BEGIN
print ('Stockname restart: ' + @stock)
SET @dateloop = '01/01/2012'
WHILE (@dateloop <= @end)
BEGIN
set @datedelta = 0
SET @dateloop = dateadd(day,1,@dateloop)
set @b = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = @dateloop and [stocks] = @stock))
WHILE (@datedelta < 4)
BEGIN
set @datedelta = @datedelta + 1
if (@b is null)
begin
SET @dateloop = dateadd(day,1,@dateloop)
set @b = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = @dateloop and [stocks] = @STOCK))
/*print ('b= ' + cast( @b as varchar(10)) + ' dateadd1=' + cast( @datedelta as varchar(10))) */
end
END
SET @datedelta = 0
set @a = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = dateadd(day,-1,@dateloop) and [stocks] = @stock))
set @c = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = dateadd(day,+96,@dateloop) and [stocks] = @stock))
if @b/@a < 0.8
begin
WHILE (@datedelta < 4)
BEGIN
set @datedelta = @datedelta + 1
if (@a is null)
begin
SET @dateloopfora = dateadd(day,-@datedelta,@dateloop)
set @a = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = @dateloopfora and [stocks] = @STOCK))
/*print ('b= ' + cast( @b as varchar(10)) + ' dateadd1=' + cast( @datedelta as varchar(10))) */
end
if (@c is null)
begin
SET @dateloopforc = dateadd(day,96+@datedelta,@dateloop)
set @c = (SELECT [val] FROM [tsxvPrices].[dbo].[3coldata] WHERE( [dates] = @dateloopforc and [stocks] = @STOCK))
/*print ('b= ' + cast( @b as varchar(10)) + ' dateadd1=' + cast( @datedelta as varchar(10))) */
end
END
/*print ('Stockname: ' + @stock)
print @dateloop
print('daily')
print @b/@a
print ('quarterly')*/
print @c/@b
/*print ('======================')*/
end
END
FETCH NEXT FROM @MYCURSOR INTO @STOCK
END
CLOSE @MYCURSOR
DEALLOCATE @MYCURSOR
答案 0 :(得分:0)
我可以立即看到一个简单的问题,你正在使用Cursor。 这可能是处理SQL的最糟糕的方法之一,它非常慢,并且它迫使SQL引擎效率非常低。
你是SQL的新手,所以我会放弃技术解释,但请看看其他StackOverflow问题:
Why is it considered bad practice to use cursors in SQL Server?
我或许可以提供进一步的建议,您使用的是什么版本的SQL?