【问题标题】:execute output parameter sql server执行输出参数sql server
【发布时间】:2014-09-21 12:07:50
【问题描述】:

我有三个参数@codetable1.column1 的任何元素,@date 是元素table2.column2 的日期,@total 将是一个输出参数,显示出现元素table2.column2 的时间.

我想执行一个程序,显示table1.column1table2.column1date_column 之间的内部连接;仅在参数引入 @date 之前的日期。

并且还返回@total中的选择行总和

create procedure pro1
    @code int, 
    @date datetime, 
    @total smallint OUTPUT
as
    select 
       table1.column1, table2.date_column
    from 
       table1 
    inner join 
       table2 on table1.column1 = table2.column2
    where 
       table1.column1 = @code 
       and table2.date_column = @date 
       and @date <= table2.date_column

【问题讨论】:

  • 你说“行的总和”——你能澄清一下吗?您的意思是“(某列)的总和”还是“行数”?

标签: sql-server stored-procedures join parameters


【解决方案1】:

如果我没看错,@total 就是返回的行数。如果确实如此,那么您可以消除重复查询的需要(加上必须处理并发问题,例如在查询之间修改数据):

create procedure pro1
(
    @code int, @date datetime, @total smallint OUTPUT
)
as
begin
select
    table1.column1,
    table2.date_column
from
    table1
    inner join
    table2 on table1.column1 = table2.column2
where
    table1.column1 = @code
    and
    table2.date_column = @date
    and
    @date <= table2.date_column;

set @total = @@rowcount;
end

【讨论】:

  • 谢谢!!,对使用rowcount函数很有用。
【解决方案2】:

在 SQL Server 中,在 select 语句中,您不能将值分配给变量并返回数据,因此您需要执行此查询两次,一次返回您期望返回的数据,一次将值分配给 @ 987654321@参数。

create procedure pro1
  @code int
 ,@date datetime
 ,@total int OUTPUT
AS
BEGIN
  SET NOCOUNT ON;
select table1.column1
    , table2.date_column
from table1 
inner join table2  on table1.column1 = table2.column2
where table1.column1 = @code 
  and CAST(table2.date_column AS DATE) = @date 
  and table2.date_column <= @date

select @total = SUM(table1.column1)
from table1 
inner join table2  on table1.column1 = table2.column2
where table1.column1 = @code 
  and CAST(table2.date_column AS DATE) = @date 
  and table2.date_column <= @date  

END

【讨论】:

  • 感谢您的帮助,只显示日期参数而不是以前的日期。
猜你喜欢
  • 2011-03-28
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多