新建一个 Table
USE [tempdb]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo]. [Test](
[ID] [int] IDENTITY ( 1, 1) NOT NULL,
[Value] [int] NOT NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH ( PAD_INDEX = OFF , STATISTICS_NORECOMPUTE = OFF , IGNORE_DUP_KEY = OFF ,ALLOW_ROW_LOCKS = ON , ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo]. [Test] ADD CONSTRAINT [DF_Test_Value] DEFAULT (( 0)) FOR [Value]
GO
插入数据:
Declare @i INT
SET @i = 2
While @i < 10000
BEGIN
INSERT INTO Test( value)
values ( @i)
SET @i = @i + 1
END
用三种方法求和,
第一种,游标:
DECLARE @I INT
DECLARE @Value INT
SET @I = 0
SET @Value = 0
DECLARE C$TestCursor CURSOR FOR
Select Value From test
OPEN C$TestCursor
Select GETDATE ()
FETCH NEXT FROM C$TestCursor INTO @Value
WHILE @@FETCH_STATUS = 0
BEGIN
SET @I = @I + @Value
FETCH NEXT FROM C$TestCursor INTO @Value
END
CLOSE C$TestCursor
DEALLOCATE C$TestCursor
Select GETDATE ()
执行三次:
1 . 2011-03-24 22:39:32.780 , 2011-03-24 22:39:33.217. 437
2 . 2011-03-24 22:40:37.750 , 2011-03-24 22:40:38.187. 437
3 . 2011-03-24 22:40:54.263 , 2011-03-24 22:40:54.717. 454
第二种, WHILE 循环:
DECLARE @MAXID INT
SELECT @MAXID = MAX ( ID) From Test
SELECT GETDATE ()
DECLARE @ID INT
DECLARE @Value INT
SET @ID = 1
SET @Value = 0
WHILE @ID <= @MAXID
BEGIN
IF EXISTS( Select ID From test WHERE ID = @ID)
BEGIN
Select @Value=( @Value+ Value) From test WHERE ID = @ID
END
SET @ID = @ID + 1
END
SELECT GETDATE ()
执行三次:
1 . 2011-03-24 23:12:01.717 , 2011-03-24 23:12:02.043. 326
2 . 2011-03-24 23:13:15.390 , 2011-03-24 23:13:15.717. 327
3 . 2011-03-24 23:13:45.560 , 2011-03-24 23:13:45.890. 330
第三种,聚合函数:
SELECT GETDATE ()
SELECT SUM ( Value) FROM Test
SELECT GETDATE ()
1 . 2011-03-24 23:05:10.170 , 2011-03-24 23:05:10.170
2 , 2011-03-24 23:06:19.840 , 2011-03-24 23:06:19.840
3 . 2011-03-24 23:06:31.623 , 2011-03-24 23:06:31.623
尽量不要使用游标,尽量用连接或者集合操作 ( joins / set operations ) 来实现,即使是 WHILE 都有可能比游标快。