【问题标题】:SQL Server: can you execute a stored procedure with an optional parameter? (See code)SQL Server:您可以执行带有可选参数的存储过程吗? (见代码)
【发布时间】:2018-09-02 14:27:28
【问题描述】:

我基本上只想返回通过参数输入的一名患者,或者如果参数中没有传递任何值,则返回所有患者。我的代码可以做到这一点吗?我不断收到此错误:

当不使用 EXISTS 引入子查询时,选择列表中只能指定一个表达式。

我的代码:

create proc getOutsideLeadPatients 
     @patient int = null
as 
begin
    if @patient is not null 
       return (select * 
               from tblpatientdemographics p 
               where exists (select * from tblDBSSurgery s 
                             where s.idpatient = p.idpatient 
                               and s.blnoutside = 1 
                               and p.idpatient = @patient))
    else if @patient is null 
       return select * 
              from tblpatientdemographics p 
              where exists (select * from tblDBSSurgery s 
                            where s.idpatient = p.idpatient 
                              and s.blnoutside = 1)
end 
go 

【问题讨论】:

  • 程序代码是高度特定于供应商的 - 所以请添加一个标签来指定您是否使用mysqlpostgresqlsql-serveroracledb2 - 或完全不同的东西。
  • 我使用的是 SQL Server 2008
  • 您不需要退货。您可以选择返回记录集。

标签: sql sql-server-2008 stored-procedures parameters


【解决方案1】:

哇,我需要做的就是摆脱回报。谢谢本!

【讨论】:

    【解决方案2】:

    这里有一个小技巧:

    create proc getOutsideLeadPatients 
         @patient int = null
    as 
    begin
    
    select * 
                   from tblpatientdemographics p 
                   where exists (select 1 from tblDBSSurgery s 
                                 where s.idpatient = p.idpatient 
                                   and s.blnoutside = 1 
                                   and p.idpatient = COALESCE(@patient, p.idpatient))
    
    
    end 
    go 
    

    也就是说 - 如果@patient 为 NULL,则将其设置为等于 p.idpatient。那么条件每次都会过去。

    【讨论】:

      【解决方案3】:

      也许可以尝试一下这条线

      SELECT p.* 
      FROM tblpatientdemographics p 
      INNER JOIN tblDBSSurgery s ON s.idpatient = p.idpatient
      WHERE (ISNULL(@patient,0) = 0 OR p.idpatient = @patient)
      AND s.blnoutside = 1
      

      正如上面 Ben 提到的,你不必使用 Return 来发回数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-16
        • 2010-12-21
        • 1970-01-01
        • 2012-10-15
        • 2018-11-08
        • 2017-11-02
        • 1970-01-01
        相关资源
        最近更新 更多