怎么写这个sql语句

ywh005 2003-08-26 07:11:59
查询条件有:
订购号(唯一),维修站号,维修站名称,生成日期,是否结算
要用户输入任何一个或几个条件都可以查询
请问这么个条件判断怎么写?????
...全文
51 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2003-08-26
  • 打赏
  • 举报
回复
用存储过程来实现:

--查询的存储过程
create procedure test
@订购号 varchar(100)
,@维修站号 varchar(100)
,@维修站名称 varchar(100)
,@生成日期 datetime
,@是否结算 bit
as
declare @tj varchar(8000)
select @tj='',@tj=@tj
+case isnull(@订购号,'') when '' then ''
else ' and [订购号]='''+@订购号+'''' end
+case isnull(@维修站号,'') when '' then ''
else ' and [维修站号]='''+@维修站号+'''' end
+case isnull(@维修站名称,'') when '' then ''
else ' and [维修站名称]='''+@维修站名称+'''' end
+case isnull(@生成日期,'') when '' then ''
else ' and [生成日期]='''+@生成日期+'''' end
+' and [是否结算]='+cast(isnull(@是否结算,0) as varchar)
if @tj<>''
set @tj=' where '+right(@tj,len(@tj)-5)

exec('select * from 表 '+@tj
go


--调用
exec test '1','','','',''
iiboy 2003-08-26
  • 打赏
  • 举报
回复
认同这个:主要是前台生成查询条件,没什么SQL技巧。
nboys 2003-08-26
  • 打赏
  • 举报
回复
把对应的值传进来:

declare @订购号 varchar(100),@维修站号 varchar(100),@维修站名称 varchar(100),@生成日期 datetime
select * from tableName where
订购号 like case when isnull(@订购号,0)='0' then '%' else 订购号 end,
and 维修站号 like case when isnull(@维修站号,0)='0' then '%' else 维修站号 end,
and 维修站名称 like case when isnull(@维修站名称,0)='0' then '%' else 维修站名称 end,
and 生成日期 like case when isnull(@生成日期,0)='0' then '%' else 生成日期 end

如果在前台,可以把对应的sql变量转换为前台语言的变量,直接在语言的sql语句中应用
nboys 2003-08-26
  • 打赏
  • 举报
回复
declare @订购号 varchar(100),@维修站号 varchar(100),@维修站名称 varchar(100),@生成日期 datetime

select * from tableName where
订购号 like case when isnull(@订购号,0)='0' then '%' else 订购号 end,
and 维修站号 like case when isnull(@维修站号,0)='0' then '%' else 维修站号 end,
and 维修站名称 like case when isnull(@维修站名称,0)='0' then '%' else 维修站名称 end,
and 生成日期 like case when isnull(@生成日期,0)='0' then '%' else 生成日期 end

txlicenhe 2003-08-26
  • 打赏
  • 举报
回复
主要是前台生成查询条件,没什么SQL技巧。
txlicenhe 2003-08-26
  • 打赏
  • 举报
回复
up
sdhdy 2003-08-26
  • 打赏
  • 举报
回复
select * from tablename
where 订购号=1 and 维修站号=132 and 维修站名称='asdf' and 生成日期='2003-08-26'...
pengdali 2003-08-26
  • 打赏
  • 举报
回复
declare @参数1 varchar(100),@参数2 varchar(100)


select * from 表 where 维修站号=isnull(@参数1,维修站号) and 维修站名称=isnull(@参数2,维修站名称)

这样你没有给值的话就会忽略
sdhdy 2003-08-26
  • 打赏
  • 举报
回复
select * from tablename
where 订购号=1 or 维修站号=132 or 维修站名称='asdf' or 生成日期='2003-08-26'...
hjb111 2003-08-26
  • 打赏
  • 举报
回复
declare @s varchar(255)
set @s='订购号=1008 and 维修站号=1004'
exec('select * from yourtable where '+@s)

在前台把输入的条件生成一个条件字符串,后台调用此字符串就可以了!

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧