如何将CTE结果分配给存储过程输出参数

时间:2014-09-17 07:12:16

标签: sql-server sql-server-2008 stored-procedures common-table-expression

这里我尝试在商店程序OUTPUR参数中返回CTE结果,我自己尝试这些,所以我不知道我在CTE中分配输出参数的问题是否正确。现在这个商店程序没有执行....请帮忙 ?在此先感谢!!!

-----Store Procedure----------
    create procedure proc_return_2val 
         @name nvarchar(60)=null,
         @name_count int output, 
         @row_count int output
    as
    begin
        select @name_count=COUNT(*) from customer_detail where customer_name like '%' + @name + '%'
        with cte as
        (
            select temp=ROW_NUMBER() over(order by(select 0)) from customer_detail
        )
        select @row_count=temp from cte;
    end

----command to display results-------
declare @a as int,@b as int
exec proc_return_2val 'am', @a output, @b output
select @a output, @b output

1 个答案:

答案 0 :(得分:1)

您的存储过程中的输出工作正常,您的问题是程序中的错误选择。您当前正在为@row_count分配多个值,只留下最后一个随机值。这是根据我的想象重写你的程序:

create procedure proc_return_2val 
  @name       nvarchar(60)=null, 
  @name_count int output, 
  @row_count  int output
as
begin
    select @name_count=COUNT(*) from customer_detail where customer_name like '%' + @name + '%'
    select @row_count =COUNT(*) from customer_detail
end

因为你坚持使用CTE for row_count。这就是你如何做到的(不是我怎么做的):

;with cte as
(
    select temp=count(*) from customer_detail
)
select @row_count=temp from cte;