Create proc testfn @counts int
as
begin
set nocount on 
create table #temptable(storeid int,storename varchar(50))

  declare @str varchar(1000) 
   set @str = 'insert into temptable '+
             'select top '+cast(@counts as varchar(10))+
              ' * from  stores'
  exec (@str)
            select * from #temptable drop table #temptable
end

解决方案 »

  1.   

    楼上的,我是要写成函数形式,因为我要在前台调用函数
    例如:
      select * from dbo.testfn(10)
      

  2.   

    測試CREATE TABLE [tabChar] (
    [id] [int] IDENTITY (1, 1) NOT NULL ,
    [name] [varchar] (10) COLLATE Chinese_Taiwan_Stroke_CI_AS NULL ,

    CONSTRAINT [PK_tabChar] PRIMARY KEY  CLUSTERED 
    (
    [id]
    )  ON [PRIMARY] 
    ) ON [PRIMARY]
    GOinsert into tabChar
    select 'aaaaa' 
    union select 'bbbbb' 
    union select 'ccccc' 
    union select 'ddddd' 
    union select 'eeeee' 
    union select 'fffff' 
    union select 'gggggg' 
    union select 'hhhhhh' 
    go
    Create proc pAA(@counts int)
    as
    begin
    set nocount on 
    create table #temptable(id int identity(1,1),storename varchar(50))

      declare @str varchar(1000) 
       set @str = 'insert into #temptable '+
                 'select top '+cast(@counts as varchar(10))+
                  ' name  from  tabChar'
      exec (@str)
                select * from #temptable drop table #temptable
    endgoexec pAA 5
    -----------------------------------------------------
    1 aaaaa
    2 bbbbb
    3 ccccc
    4 ddddd
    5 eeeee
      

  3.   

    我知道用存取过程是可以实现,但我的前台程序是用Select语句调用的,所以我只好写成函数形式啊,请指教!
      

  4.   

    那我只好等待有心人出现帮我了,不过还是要多谢你啊,progress99(如履薄冰)
      

  5.   

    但我的前台程序是用Select语句调用的你也可以在前台這麼處理:
    1.建臨時表或表變量
    2.insert into 臨時表或表變量
    exec 存儲過程3.
    select * from 臨時表或表變量關注高手的好方法
      

  6.   

    --函数的方法:Create function testfn(@counts int)
    returns @temptable table(storeid int,storename varchar(50))
    as
    begin
    declare @r table(id int identity(1,1),storeid int,storename varchar(50))
    insert @r select * from  stores
    insert @temptable select storeid,storename
    from @r where id<=@counts
    return
    end
    go
      

  7.   

    --如果storeid 是主键,可以用:
    Create function testfn(@counts int)
    returns @temptable table(storeid int,storename varchar(50))
    as
    begin
    insert @temptable select storeid,storename from stores a
    where (select sum(1) from stores where storeid<=a.storeid)<=@counts
    return
    end
    go
      

  8.   

    邹健兄,--如果storeid 是主键,可以用的方法是不是可以改成一下方法会更容易理解呢?
    Create function testfn(@counts int)
    returns @temptable table(storeid int,storename varchar(50))
    as
    begin
    insert @temptable select storeid,storename 
             from stores a
    where (select count(*) 
                    from stores 
                    where storeid<=a.storeid)<=@counts
    return
    end
    go
      

  9.   

    这是各人的习惯问题,我觉得用sum(1)少打几个字而已,而且习惯了