存储过程中根据参数的空值与否拼接语句

本文介绍了一种使用存储过程实现动态SQL查询的方法。通过参数化输入,存储过程能够灵活地构造查询条件,支持多种组合查询场景。文章展示了如何根据不同参数构建SQL语句,并通过实例演示了不同类型参数的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 题:存储过程有4个参数,1个是数据表名,3个是数据字段,
    在这3个数据字段中,至少有一个数据字段参数不为空。

我的方式是:由于有3个不确定空值与否的参数,查询语句也不确定,可以根据判断,得出查询语句。
存储过程我是这样写的

if exists (select name from sysobjects where name = 'MyProcedurePD' and type = 'p')
drop procedure MyProcedurePD
go

create  PROCEDURE MyProcedurePD
--参数---

@tablename nvarchar(20), --表名
@var1 nvarchar(20)='',  --参数1
@var2 nvarchar(20)='',  --参数2
@var3 nvarchar(20)=''  --参数3

As

BEGIN
--初始化空值参数-----------

if(@var1 is null)
set @var1=''

if(@var2 is null)
set @var2=''

if(@var3 is null)
set @var3=''

--初始化查询语句-----------

declare @where nvarchar(4000)
set @where =''

if(len(@var1)>0)
begin
if(len(@where)=0)
begin
set @where=@where +'ywlbid = '''+@var1+''''
end
else
begin
set @where=@where +'and ywlbid = '''+@var1+''''
end
end

if(len(@var2)>0)
begin
if(len(@where)=0)
begin
set @where=@where +'ywid = '''+@var2+''''
end
else
begin
set @where=@where +'and ywid = '''+@var2+''''
end
end

if(len(@var3)>0)
begin
if(len(@where)=0)
begin
set @where=@where +'ywxid = '''+@var3+''''
end
else
begin
set @where=@where +'and ywxid = '''+@var3+''''
end
end


if(len(@where)>0)
 set @where =' WHERE '+@where
declare @SQLCOUNT nvarchar(4000);

set @SQLCOUNT =' select * from '+@tablename+''+ @where

EXEC (@SQLCOUNT)

END

下面这个的看点是:参数的类型(int)与变量类型(nvarchar)不同

CREATE PROCEDURE ST_ShowRoomByCatgAndStatus2(
                         @RCategoryId int,@Status int)
 AS
 DECLARE @str   nvarchar(1000)
set @str=''--要赋初值,不然为NULL
 if @RCategoryId!=0
 BEGIN
 SET @str =  @str + '  and r.ST_RCategoryId=' + rtrim(@RCategoryId)--转为字符型再相加
 END
 if @Status!=0
 BEGIN
 SET @str = @str + '  and s.ST_Status='  + rtrim(@Status)
 END
 
select @str='
       select     r.ST_RoomId, c.ST_Name,s.ST_Status
       from         ST_RoomsInfo r, ST_RoomCategory c, ST_RoomStatus s
       where      s.ST_RoomId=r.ST_RoomId
                       and c.ST_RCategoryId=r.ST_RCategoryId '+ @str
exec(@str)
GO

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值