2014-09-21 75 views
1

我有三个参数@codetable1.column1任何元件,@date是元件table2.column2的日期和@total将是示出了出现在元件table2.column2时代的输出参数。执行输出参数SQL服务器

我想执行一个程序,显示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 
+0

您说“行数之和” - 你能澄清吗?你的意思是“(某些列的总和)”或“行数”? – 2014-09-21 15:17:30

回答

0

如果我正确的读了你,@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 
+0

谢谢!!,使用rowcount函数很有用。 – 2014-09-21 19:54:43

0

返回的行选择和在SQL Server中,在SELECT语句中你不能赋值给一个变量,并返回数据,因此,你需要两次执行这个查询,一次返回您期待回来的数据,一次为@Total参数赋值。

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 
+0

感谢您的帮助,只显示日期参数而不是以前的日期。 – 2014-09-21 15:35:38