【发布时间】:2015-04-08 05:48:41
【问题描述】:
你好朋友我对sql server有一点疑问请告诉我如何解决
表:
patient:
pid | Date | Name
100 | 2015-01-01 |Abc
101 | 2015-02-20 |banu
102 |2015-03-14 |hari
`
Address:
Pid | Fromdate | ToDate | Address
100 | 2014-12-31 | 2015-02-01 | Hyd
101 | 2015-02-20 |2015-02-20 | Bang
102 | 2015-04-10 |2015_05_20 | Chen`
根据上表,我想在地址表中检查从日期到今天之间的患者日期。 如果患者日期介于 fromdate 和 todate 在地址中,我想加载单独的临时表 在 tempresult 表中,我只需要患者的姓名列,并且为了识别该记录添加一个 列状态。 f 患者日期不在 fromdate 和 todate 之间 在 tempresult 表中。 Finaly Temp 表结果如下所示:
Tablesname :##TempResult
Name | Status
Abc | Outdate
banu | Indate
hari | outdate
我尝试如下
alter procedure test
as
begin
IF
OBJECT_ID('tempdb..##Result') IS NOT NULL
drop
table ##Result
create
table ##Result
(
Name
varchar(50),
Filter
varchar(10)
)
insert
into ##result
select
a.name, 'InDate' as Filter from patient a join address b on a.patientnumber=b.patientnumber
where
a.date <=b.fromdate and a.date >=b.todate
insert into ##result
select
a.name, 'outDate' as Filter from patient a join address b on a.patientnumber=b.patientnumber
where
a.date <>b.fromdate and a.date <>b.todate
select * from ##result
end
exec test
select * from ##result
它给出了正确的值。但性能方面它不是好方法 到期记录检查 2 次(全部记录)请告诉我任何其他方式 达到这个问题。 我尝试过的另一种方式
alter procedure [dbo].[FindDate]
as
begin
IF OBJECT_ID('tempdb..##Address') IS NOT NULL
drop table ##Address
create table ##Address
(
id int identity(1,1),
patientnumber int,
fromdate date,
Todate date,
Address varchar(50)
)
IF OBJECT_ID('tempdb..##Result') IS NOT NULL
drop table ##Result
create table ##Result
(
Name varchar(50),
Filter varchar(10)
)
insert into ##Address
select patientnumber,fromdate,todate,address from Address
----------------------------------------------------
declare @acount int
select @acount=count(id) from ##Address
declare @i int
set @i=1
while @i<=@acount
begin
declare @pn int,@fromdate date,@todate date,@address varchar(50)
select @pn=patientnumber,@fromdate=fromdate,@todate=Todate from ##Address
where id=@i
set @i=@i+1
end
declare @bcount int
declare @in int
set @in=1
while @i<=@bcount
begin
select @bcount=count(1) from patient
where patientnumber=@pn and [patient].[date] between @fromdate and @todate
if @bcount<>0
begin
insert into ##Result
select name,'InDate' as Filter from patient
where patientnumber=@pn
end
else
print '4'
begin
insert into ##Result
select name,'OutDate' as Filter from patient
where patientnumber=@pn
end
---set @i=@i+1;
select * from ##Result
end
end
这个结果不好,需要更多时间来记录 3 条记录。 请告诉我如何在 sql server 中解决这个问题。
【问题讨论】:
标签: sql-server sql-server-2008 sql-server-2012