读书人

output取值的有关问题

发布时间: 2013-10-19 20:58:22 作者: rapoo

output取值的问题


DECLARE @id int;

INSERT
INTO [testtable]
([name])
output inserted.id --into @temptable 只能用插入临时表的方法获取值吗?
VALUES
('test')


使用output 只能用 into @temptable的方式取值吗?
可不可以直接赋值给 @id?
[解决办法]

以下示例将行插入 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



[解决办法]
你是table结构是什么样的?有没有自动递增的id,如果有:select @@identity
[解决办法]
不能直接赋值给 @id
先使用output into @temptable
再:select top 1 @id=id from @temptable

[解决办法]
你只能插入到表变量里面,而不能是变量
先定义一个变变量
declare @tb table(id int)

然后类似下面的
delete from test2 output deleted.id into @tbwhere [no]=1

update test2 set n='ccc' output
inserted.no into @tb
where [no]=3

select * from @tb
[解决办法]

declare @id int
declare @temptable table(id int)

INSERT INTO [testtable]([name])
output inserted.id into @temptable
values('test')

select @id=id from @temptable

select @id 'id'

读书人网 >SQL Server

热点推荐