我有以下代码,但不想多次引用表 @test 及其基本 where 子句,我尝试使用 ROWCOUNT 重构它,但无法解决它。
select *
from @test2
where userid = @userid
and (
ExpiryDate > getdate()
or
not exists(select * from @test2
where userid = @userid
and ExpiryDate > Getdate()
and Status = 40)
)
这是我用于测试的数据:
declare @test2 table(ID int, ExpiryDate datetime, userid int, siteid int, Status int)
insert into @test2 (ID, ExpiryDate, userid, siteid, Status)
--not expired/status=40 and not status=40 entries
select 1, '2013-08-16', 1, 1, 40
union
select 2, '2013-08-16', 1, 1, 10
union
--not expired/status=40 and status=40 entries
select 3, '2013-08-16', 2, 2, 40
union
select 4, '2013-08-16', 2, 2, 40
union
--expired/status=40 and not status=40 entries
select 5, '2013-08-13', 3, 3, 40
union
select 6, '2013-08-16', 3, 3, 10
union
--expired/status=40 and status=40 entries
select 7, '2013-08-13', 4, 4, 40
union
select 8, '2013-08-16', 4, 4, 40
union
--not expired/status=40 single entry
select 9, '2013-08-16', 5, 5, 40
union
--expired/status=40 single entry
select 10, '2013-08-13', 6, 6, 40
/* scenarios:
not expired/status=40 and not status=40 entries - sees both - userid = 1
not expired/status=40 and status=40 entries - sees both - userid = 2
expired/status=40 and not status=40 entries - sees both - userid = 3
expired/status=40 and status=40 entries - sees single - userid = 4
not expired/status=40 single entry - sees single - userid = 5
expired/status=40 single entry - sees single - userid = 6
*/
我什至不确定是否可以重构它。任何有任何想法如何改进这一点的人都会非常感激。
谢谢
约翰