如何Delete掉这些数据?
有这样一个表A
a b c
-----------------------
1 cat 2006/4/11
2 bee 2006/5/7
3 dea 2006/7/22
4 kle 2007/3/1
5 soe 2006/4/21
6 que 2005/11/7
7 jkc 2007/2/27
8 ore 2007/6/12
要实现这样一个存储过程:通过传入参数正整数k,删除表A中月份最早的k个月的行。
应该如何实现?
[解决办法]
if object_id( 'tbTest ') is not null
drop table tbTest
if object_id( 'spTest ') is not null
drop proc spTest
GO
create table tbTest(a int, b varchar(10),c datetime)
insert tbTest
select 1, 'cat ', '2006/4/11 ' union all
select 2, 'bee ', '2006/5/7 ' union all
select 3, 'dea ', '2006/7/22 ' union all
select 4, 'kle ', '2007/3/1 ' union all
select 5, 'soe ', '2006/4/21 ' union all
select 6, 'que ', '2005/11/7 ' union all
select 7, 'jkc ', '2007/2/27 ' union all
select 8, 'ore ', '2007/6/12 '
GO
----创建存储过程
CREATE PROC spTest @k int
AS
declare @sql varchar(1000)
set @sql = '
DELETE tbTest WHERE convert(varchar(7),c,120) IN(
select top ' + rtrim(@k) + ' convert(varchar(7),c,120) from tbTest group by convert(varchar(7),c,120) order by 1) '
EXEC(@sql)
GO
----执行存储过程(当@k=2时,删除2005/11月和2006/04月的行)
declare @k int
set @k = 2
EXEC spTest @k
----查看删除结果
select * from tbTest order by c
----清除测试环境
drop proc spTest
drop table tbTest
/*结果
a b c
----------- ---------- ------------------------------------------------------
2 bee 2006-05-07 00:00:00.000
3 dea 2006-07-22 00:00:00.000
7 jkc 2007-02-27 00:00:00.000
4 kle 2007-03-01 00:00:00.000
8 ore 2007-06-12 00:00:00.000
*/