sql sever经典语句

来源:互联网 发布:js随机生成字母和数字 编辑:程序博客网 时间:2024/05/25 21:32
前一段时间总是为一种查询语句而苦恼,多重筛选条件,同时任意筛选条件都可以为空,且为空时即为不需要该筛选条件,不为空时附加该筛选条件。这该怎么写好呢?前台判断为不为空不好处理,难道针对每一种情况写条语句?这样的话,四个查询条件,2*2*2*2=16,这显然有点离谱。在数据库里写IF逻辑语句,看似行得通,实际上更为痛苦!百思不得如何写。一次偶然的机会让我在网上发现了这么条句型就解决问题了,真是欣喜若狂啊,下面分享给一样为复杂的SQL语句而苦恼的朋友们,此经典句型还是值得珍藏。

create proc pc_searchDispose
@dateone datetime,
@datetwo datetime,
@domestic bit,
@drug_type smallint,
@category smallint,
@special_composition smallint
as
SET XACT_ABORT ON
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
begin
select sd.drug_id,convert(char(10),sd.date,23) as disDate,sd.batchNum,sd.quantity,sd.origin,sd.Reason,sd.disposeOpinion,sd.disposeMethod,sd.remark,convert(char(7),st.validity,23) as validity,
su.spuplierName,d.drug_name,d.drug_specification,d.manufacturer_id,d.units,d.costprice,d.domestic,d.drug_type,d.category,d.specia_composition,sp.class_name as types into #aa from stock_dispose sd
join drug_document d on sd.drug_id=d.drug_id
join stock_drug st on sd.drug_id=st.drug_id and sd.batchNum=st.batch_number
left join suppliers su on sd.supplierID=su.supplierId
left join system_parameter sp on d.types=sp.class_id and sp.label_id='01'
where convert(char(10),sd.date,23) between convert(char(10),@dateone,23) and convert(char(10),@datetwo,23)

select * from #aa where (@domestic is null or domestic=@domestic) and (@drug_type is null or drug_type=@drug_type) and (@category is null or category=@category) and (@special_composition is null or specia_composition=@special_composition)
drop table #aa
end

 

重点红色部分条件语句。

SQL还是很强大的啊,有待学习……

原创粉丝点击