如何写一存储过程实现以下功能:

valu 2009-10-09 11:01:52
create procedure sp_select_area
@id int
as
begin
--默认选择所有地区
select * from area
end



@id 为空时选择所有地区
@id 不为空时,选择指定的地区
如何实现?
...全文
170 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
valu 2009-10-10
  • 打赏
  • 举报
回复
请问7楼,在asp.net里怎么实际可能为null的参数传递呢?
百年树人 2009-10-10
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 valu 的回复:]
create procedure sp_select_area
    @id int,
    @city nvarchar(20),
    @is_zx tinyint
as
begin
    --默认选择所有地区
    select * from area
end


如果有多个参数呢?
[/Quote]

create procedure sp_select_area
@id int=null,
@city nvarchar(20)=null,
@is_zx tinyint=null
as
begin
--默认选择所有地区
select * from area
where id=isnull(@id,id)
and city=isnull(@city,city)
and is_zx=isnull(@is_zx,is_zx)
end
go
q85958341 2009-10-10
  • 打赏
  • 举报
回复

create procedure sp_select_area
@id int=null,
@city nvarchar(20)=null,
@is_zx tinyint=null
as
begin
--默认选择所有地区
select * from area
where id=isnull(@id,id)
and city=isnull(@city,city)
and is_zx=isnull(@is_zx,is_zx)
end
go

老七 2009-10-10
  • 打赏
  • 举报
回复
7楼简洁明了
navy887 2009-10-10
  • 打赏
  • 举报
回复
create procedure sp_select_area 
@id int,
@city nvarchar(20),
@is_zx tinyint
as
begin
if @id is null
select * from area
else
select * from area where area=@city
end
yuzhifu1 2009-10-10
  • 打赏
  • 举报
回复
学习
qiqi860819 2009-10-10
  • 打赏
  • 举报
回复

create procedure sp_select_area
@id int
as
begin
declare @str varchar(1024)
set @str='select * from area where 1=1';
if @id is not null
set @str=@str+' and id='+cast(@id as varchar(4))+'';
exec (@str)
end

guguda2008 2009-10-10
  • 打赏
  • 举报
回复
自己在程序里先判断一下
bancxc 2009-10-09
  • 打赏
  • 举报
回复

--可以这样写
create procedure sp_select_area
@id int null,
@city nvarchar(20) null,
@is_zx tinyint null
as
begin

declare @strwhere nvarchar(4000)

set @strwhere = ' 1=1'
if @id is not null
set @strwhere = @strwhere + ' and id='+@id

if @city is not null
set @strwhere = @strwhere + ' and city='''+@city''''
if @city is not null
set @strwhere = @strwhere + ' and is_zx='+@is_zx
exec('select * from area where '+@strwhere)
end

bancxc 2009-10-09
  • 打赏
  • 举报
回复
只能多个
if
elseif
....
else
valu 2009-10-09
  • 打赏
  • 举报
回复
create procedure sp_select_area
@id int,
@city nvarchar(20),
@is_zx tinyint
as
begin
--默认选择所有地区
select * from area
end


如果有多个参数呢?
bancxc 2009-10-09
  • 打赏
  • 举报
回复
create procedure sp_select_area 
@id int = null
as
begin
if @id is null
select * from area
else
select * from area where id=@id
end
lunzi028 2009-10-09
  • 打赏
  • 举报
回复
只要有 id 和area 的关系
用if else 即可
rucypli 2009-10-09
  • 打赏
  • 举报
回复
create procedure sp_select_area
@id int = null
as
begin
if @id is null
select * from area
else
....
end

34,594

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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