zoukankan      html  css  js  c++  java
  • 查询条件可变的存储过程

    ----查询条件可变的存储过程
    alter proc usp_guestsearch
    @guestname nvarchar(50)=null,                       ----创建存储过程定义多个变量,并赋予默认值为null
    @guestcardid nvarchar(50)=null
    as 
    declare @sql nvarchar(2000)='select * from guest '  ----创建无条件语句的SQL语句
    declare @haswhere bit=0                             ----定义变量表示是否含有where语句,初始值为0(否)
        if(@guestname is not null)                      ----如果变量不为空,因为是第一个变量,所以不用判断是否含有where(必定没有)
                begin
                    set @sql+=' where guestname=@name'  ----SQL语句拼接带有where的条件,
                    set @haswhere=1                     ----将haswhere改为1(是)表示已包含where语句
                end                               
        if(@guestcardid is not null)                    
            if(@haswhere=0)                             ----判断是否含有where
                begin 
                    set @sql+=' where guestcardid=@guestcardid'
                    set @haswhere=1
            end
            else 
            set @sql+= ' and guestcardid=@guestcardid'
    
    exec sp_executesql @sql, N'@name nvarchar(50)',@name=@guestname     ---执行拼接后的SQL语句
    go
    
    -------------执行拼接后的SQL语句,为调用存储过程sp_executesql
    -------------这部分需要注意,因为拼接后的SQL语句实际是字符串,不属于语句,所以执行存储过程需要三个变量:
                                                                                                    ------1、SQL语句
                                                                                                    ------2、定义变量
                                                                                                    ------3、变量接受存储过程传递进来的参数
    -------------示例:select * from guest where guestname=@name  @name nvarchar(50), @name=@guestname
  • 相关阅读:
    office 2007 验证失败的解决方法
    google开不了(解决办法)
    Mobilenet V1
    Windows10系统下IDECLion的安装与配置
    单目相机成像过程
    C++中如何在函数中返回局部变量的指针/引用/地址?
    ResNeXt论文阅读笔记.md
    Mobilenet V2
    Xception
    InceptionV4
  • 原文地址:https://www.cnblogs.com/ianism/p/4271492.html
Copyright © 2011-2022 走看看