在存储过程中top为传进来的可变值怎么拼接才不报错?ALTER PROCEDURE [dbo].[sp_DDK_ElecGoods]
@changeNum int --购买的数量

select top @changeNum @_cards=(case when @_cards='' then GiftCardNo else (@_cards+','+GiftCardNo) end ) from dbo.ElecGoods
where ElecGoodType=@ElecGoodType and GiftCardStatus=1 and GiftCardDistributionStatus=0  top @changeNum这样使用不对,那应该怎么用呢?还是根本上就不能这样子用?

解决方案 »

  1.   


    alter PROCEDURE [dbo].[sp_DDK_ElecGoods]
    (
    @changeNum int, --购买的数量
    @_cards varchar(300),--这个变量你没有定义?
    @ElecGoodType varchar(300)--这个变量你也没有定义?
    )
    as
    begin
    declare @sql varchar(8000)
    set @sql='select top '+ltrim(@changeNum)+ ' '+@_cards+'=(case when '+@_cards+
    '='''' then GiftCardNo else ('+@_cards+''',''+GiftCardNo) end ) from dbo.ElecGoods
    where ElecGoodType='+@ElecGoodType+' and GiftCardStatus=1 and GiftCardDistributionStatus=0 ' 
        exec(@sql)
    end类似于这样
      

  2.   

    不动态拼接的话,这样:create table test0805(id int)
    insert into test0805
    select 1 union all
    select 2 union all
    select 3 union all
    select 4 union all
    select 5declare @i int;set @i=2
    select top (@i) * from test0805
    /*
    id
    -----------
    1
    2
    */
      

  3.   

    2005以上可以直接在TOP后面跟变量2000的话需要动态拼接
      

  4.   

    select top(@changeNum) @_cards=(case when @_cards='' then GiftCardNo else (@_cards+','+GiftCardNo) end ) from dbo.ElecGoods看看!
      

  5.   

    select top @changeNum @_cards=问题应该出在@_cards= 
    字段名是不能使用变量@_cardsr的,不是top @changeNum 的问题
      

  6.   


    select top (@v) * from table
      

  7.   

    select top (@v) * from table
      

  8.   


    select top (@v) * from table