加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql-server – SQL语句在where子句中用于搜索数据库

发布时间:2020-12-12 16:12:25 所属栏目:MsSql教程 来源:网络整理
导读:我正在创建一个存储过程来返回搜索结果,其中一些参数是可选的. 我想要一个“if语句”在我的where子句,但不能让它工作. where子句只能使用非空参数进行过滤. 这是sp ALTER PROCEDURE spVillaGet -- Add the parameters for the stored procedure here@accomoda
我正在创建一个存储过程来返回搜索结果,其中一些参数是可选的.

我想要一个“if语句”在我的where子句,但不能让它工作. where子句只能使用非空参数进行过滤.

这是sp

ALTER PROCEDURE spVillaGet 
-- Add the parameters for the stored procedure here
@accomodationFK int = null,@regionFK int = null,@arrivalDate datetime,@numberOfNights int,@sleeps int = null,@priceFloor money = null,@priceCeil money = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
select tblVillas.*,tblWeeklyPrices.price from tblVillas
INNER JOIN tblWeeklyPrices on tblVillas.villaId = tblWeeklyPrices.villaFK
where 
    If @accomodationFK <> null then
        accomodationTypeFK = @accomodationFK 
     @regionFK <> null Then
        And regionFK = @regionFK 
    IF @sleeps <> null Then
        And sleeps = @sleeps 
    IF @priceFloor <> null Then
        And price >= @priceFloor And price <= @priceCeil


END

任何想法如何做到这一点?

解决方法

select tblVillas.*,tblWeeklyPrices.price 
from tblVillas
INNER JOIN tblWeeklyPrices on tblVillas.villaId = tblWeeklyPrices.villaFK
where (@accomodationFK IS null OR accomodationTypeFK = @accomodationFK)
  AND (@regionFK IS null or regionFK = @regionFK)
  AND (@sleeps IS null OR sleeps = @sleeps)
  AND (@priceFloor IS null OR (price BETWEEN @priceFloor And @priceCeil))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读