DECLARE @id int;INSERT 
INTO [testtable] 
([name]) 
output inserted.id --into @temptable 只能用插入临时表的方法获取值吗?
VALUES 
('test')
使用output 只能用 into @temptable的方式取值吗?
可不可以直接赋值给 @id?

解决方案 »

  1.   


    create proc test(@sm varchar(100) output)
    as
    begin
      set @sm='这个是返回值!'
    end
    exec test @sm=''
      

  2.   

    相当与在存储过程里面写了一个 declare @sm varchar(100)
    set @sm='这个是返回值!'
    select @sm as sm
      

  3.   

    谢谢你的回复,但是我说的是 insert, update,delete 的output返回修改行数据的问题。
    不是存储过程的output
      

  4.   


    以下示例将行插入 ScrapReason 表,并使用 OUTPUT 子句将语句的结果返回到 @MyTableVar table 变量。由于 ScrapReasonID 列使用 IDENTITY 属性定义,因此未在 INSERT 语句中为该列指定一个值。但应注意,数据库引擎为该列生成的值在 INSERTED.ScrapReasonID 列中的 OUTPUT 子句中返回。
    USE AdventureWorks;
    GO
    DECLARE @MyTableVar table( ScrapReasonID smallint,
                               Name varchar(50),
                               ModifiedDate datetime);
    INSERT Production.ScrapReason
        OUTPUT INSERTED.ScrapReasonID, INSERTED.Name, INSERTED.ModifiedDate
            INTO @MyTableVar
    VALUES (N'Operator error', GETDATE());--Display the result set of the table variable.
    SELECT ScrapReasonID, Name, ModifiedDate FROM @MyTableVar;
    --Display the result set of the table.
    SELECT ScrapReasonID, Name, ModifiedDate 
    FROM Production.ScrapReason;
    GO
      

  5.   

    嗯,这个我知道,
    我问的是可不可以把output的值直接给变量,而不是给表
    我代码应该写的有
      

  6.   

    你是table结构是什么样的?有没有自动递增的id,如果有:select @@identity
      

  7.   

    不能直接赋值给 @id
    先使用output into @temptable
    再:select top 1 @id=id from @temptable
      

  8.   

    你只能插入到表变量里面,而不能是变量
    先定义一个变变量
    declare @tb table(id int)然后类似下面的
    delete from test2 output deleted.id into @tbwhere [no]=1update test2 set n='ccc' output
    inserted.no into @tb
    where [no]=3select * from @tb
      

  9.   

    select @@identity 是返回,所有变动表自动递增的id。
    多个表同时改动的话,@@identity只返回最后一个成功的id。用的时候有危险
      

  10.   

    如果你的这个字段是自增类型的你直接在你的insert update 语句后面
    select @id=@@identity 就可以了
      

  11.   

    没办法的,
    即使output inserted.id into .. 只指定了一个id字段,但MSSQL依然需要以表的方式传,因为这里可以写多个字段(如output inserted.*),且可能是多行的,靠一个变量是无法存储的.
    而表的方式存储是通用的.
      

  12.   


    declare @id int
    declare @temptable table(id int)INSERT INTO [testtable]([name]) 
     output inserted.id into @temptable
     values('test')select @id=id from @temptableselect @id 'id'
      

  13.   

    刚才试了一下,确实不能用单个变量,只能定义表变量,这个应该是sql server的硬性限制,可能是考虑到dml操作,会有多条记录,而不是一条记录吧,才作了这个限制。
    drop table t
    go
    create table t(vid int not null,pic varchar(10) not null)insert into t
    values(1,'abc'),
          (2,'def'),
          (3,'hjkl')--declare @temp table(vid int,pic varchar(10))declare @i int
    declare @pic varchar(10)delete from t
    output deleted.vid,            --引用所有字段deleted.*
           deleted.pic into @i,@pic
    where vid < 100
    /*
    消息 102,级别 15,状态 1,第 22 行
    ',' 附近有语法错误。
    */