存储过程的语法问题(100分)

chenhongjun0624 2013-03-08 04:28:13

create proc testName
@ContactName varchar(20),
@ContactTitle varchar(20),
@ContactAddress varchar(20)
as
begin
select * from Customers
where ...
end

判断传递进来的3个参数是否为空 如果不为空就添加到后面的where条件中
我知道用if判断,但是不知道语法如何写
...全文
281 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenhongjun0624 2013-03-08
  • 打赏
  • 举报
回复
引用 7 楼 hjywyj 的回复:
引用 6 楼 chenhongjun0624 的回复:引用 4 楼 hjywyj 的回复:引用 2 楼 chenhongjun0624 的回复:引用 1 楼 hjywyj 的回复:try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is n……
嗯 知道了。
  • 打赏
  • 举报
回复
引用 6 楼 chenhongjun0624 的回复:
引用 4 楼 hjywyj 的回复:引用 2 楼 chenhongjun0624 的回复:引用 1 楼 hjywyj 的回复:try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=Contac……
转义字符,字符串里面两个单引号代表一个单引号
chenhongjun0624 2013-03-08
  • 打赏
  • 举报
回复
引用 4 楼 hjywyj 的回复:
引用 2 楼 chenhongjun0624 的回复:引用 1 楼 hjywyj 的回复:try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@Cont……

and ContactName='''+@ContactName+''''
比如这边 那么多的引号
chenhongjun0624 2013-03-08
  • 打赏
  • 举报
回复
谢谢。
引用 4 楼 hjywyj 的回复:
引用 2 楼 chenhongjun0624 的回复:引用 1 楼 hjywyj 的回复:try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@Cont……
大牛 能不能解释一下涉及的''这些引号的意思啊
  • 打赏
  • 举报
回复
引用 2 楼 chenhongjun0624 的回复:
引用 1 楼 hjywyj 的回复:try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@ContactAddress is null or @Cont……
那就用3L的方法拼sql吧
szm341 2013-03-08
  • 打赏
  • 举报
回复


create proc testName
@ContactName varchar(20),
@ContactTitle varchar(20),
@ContactAddress varchar(20)
as
begin
declare @sql nvarchar(max),@whereSql nvarchar(max)
set @whereSql=''
if @ContactName<>'' set @whereSql=@whereSql+' and ContactName='''+@ContactName+''''
if @ContactTitle<>'' set @whereSql=@whereSql+' and ContactTitle='''+@ContactTitle+''''
if @ContactAddress<>'' set @whereSql=@whereSql+' and ContactAddress='''+@ContactAddress+''''

set @sql= 'select * from Customers where 1=1'+@whereSql

exec(@sql)
end

chenhongjun0624 2013-03-08
  • 打赏
  • 举报
回复
引用 1 楼 hjywyj 的回复:
try SQL code?1where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@ContactAddress is null or @ContactAddress=Contact……
我是想 如果为空就不出现where条件中
  • 打赏
  • 举报
回复
try
where (@ContactName is null or @ContactName=ContactName) and (@ContactTitle is null or @ContactTitle=ContactTitle) and (@ContactAddress is null or @ContactAddress=ContactAddress) 

22,207

社区成员

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

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