mssql 语句判断,存储过程最好

数据库有几个字段, 自增长ID,货号,现价,原价,活动开始,结束时间,是否禁用等字段现在判断: 1)开始和结束时间都不为空; 2)当前时间在开始结束时间之间; 3)现价不等于0.00 满足以上前三条都显示现价,前3条有一条不满足就显示原价或者把原价赋值给现价显示现价若该商品属性是禁用则排除该条数据
我要获取的是一个datatable

第1个回答  2013-07-22
因为没有你表格的代码,所以没有测试.存储过程PROC_1 默认表明为table_Name.
有问题可以直接问我.
CREATE PROC PROC_1
AS
DECLARE mycursor cursor for select ID,货号,现价,原价,开始时间,结束时间,禁用into #t from table_Name where 禁用=0
DECLARE @id int,@artNo varchar(20),@cp money,@op money,@startTime datetime,@endtime datetime,@status binary;
declare @conditionCount int;--3个条件中满足的条件数.
open mycursor;
fetch next from mycursor into @id,@artNo,@cp,@op,@startTime,@endtime,@status;
if(@@fetch_status=0)
BEGIN
set @conditionCount=0;
if(@startTime is not null and @endTime is not null) select @conditionCount=@conditionCount+1;
if(@startTime < getdate() and @endTime >getdate()) select @conditionCount=@conditionCount+1;
if(@cp>0) select @conditionCount=@conditionCount+1;
if (@conditionCount<3) update table_Name set 现价=@op;--3个条件有一个不满足就把现价定为原价
fetch next from mycursor into @id,@artNo,@cp,@op,@startTime,@endtime,@status;
END
select * from table_name;
go
第2个回答  2013-07-22
SELECT ID, 货号, CASE WHEN 开始时间<=GETDATE() AND 结束时间>=GETDATE() AND 现价<>0
                        THEN 现价 
                        ELSE 原价 END AS '现价'        
    FROM TABLE WHERE 禁用<>1

这样也能达到你要的效果。

第3个回答  2013-07-20
select ID,货号,现价,开始时间,结束时间,禁用 from tablename
where (开始时间 IS NOT NULL )
AND (结束时间 IS NOT NULL )
AND (开始时间 <= GETDATE())
AND (结束时间 >= GETDATE())
AND (现价 > 0)
UNION ALL
select ID,货号,原价 as 现价,开始时间,结束时间,禁用 from tablename
where (开始时间 IS NULL )
OR (结束时间 IS NOT NULL )
OR (开始时间 > GETDATE())
OR (结束时间 < GETDATE())
OR (现价 = 0)
这里现价设为大于0,是认为价格不为负数。本回答被提问者采纳