SQL SERVER 游标使用
本文主要就一个百度知道上的问题,介绍游标的用法,以及循环语句的使用。
题目:
假设下边的数据为2014用户,在2009年1月,写出可以计算出2014用户在2009年1月连续出勤的记录.连续出勤指的是用户在2007年1月份连续出勤,中间没有一天间断的 就比如2007-01-04 到 2007-01-08~~~~2007-01-11这个中间连着5天没有出勤 看看这些就是连续(只要是包括两天及两天以上的就是) 2007-01-08~~~~~2007-01-11
2007-01-13~~~~~2007-01-15
2007-01-17~~~~~2007-01-18
2007-01-20~~~~~2007-01-23
解决思路:
创建表aaaa,录入数据如下:
2014 2009-01-01 00:00:00.000
2014 2009-01-02 00:00:00.000
2014 2009-01-03 00:00:00.000
2014 2009-01-10 00:00:00.000
2014 2009-01-11 00:00:00.000
2014 2009-01-12 00:00:00.000
2014 2009-01-18 00:00:00.000
2014 2009-01-20 00:00:00.000
游标语法:
Transact-SQL 语法
DECLARE cursor_name CURSOR
[ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ]
[ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ]
[ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ]
[ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ]
解决方法:
DECLARE @riqi datetime,@jieguo varchar(50)
DECLARE riqi_cursor CURSOR FOR
SELECT riqi
FROM aaaa
WHERE [user]=2014
ORDER BY riqi
OPEN riqi_cursor
FETCH NEXT FROM riqi_cursor INTO @riqi
WHILE @@FETCH_STATUS = 0
BEGIN
set @jieguo=CAST(@riqi as varchar) + '-'
while (select count(*) from aaaa where riqi=DATEADD(day, 1, @riqi))>=1
begin
FETCH NEXT FROM riqi_cursor INTO @riqi
end
set @jieguo=@jieguo + CAST(@riqi as varchar)
PRINT @jieguo
FETCH NEXT FROM riqi_cursor INTO @riqi
END
CLOSE riqi_cursor
DEALLOCATE riqi_cursor
GO
结果如下:
01 1 2009 12:00AM-01 3 2009 12:00AM
01 10 2009 12:00AM-01 12 2009 12:00AM
01 18 2009 12:00AM-01 18 2009 12:00AM
01 20 2009 12:00AM-01 22 2009 12:00AM