日期:2014-05-18  浏览次数:20460 次

MSSQL关于插入记录返回新插入ID,ID为NEWID()生成!
在MSSQL中
if exists (select name from sysobjects where name='#temp')
drop table #temp
go
create table #temp
(
id nvarchar(100) default(newid()),
name nvarchar(10) default('空')
)

go

insert into #temp (name) values ('fads')
这里要return 刚才插入那条记录的ID
这里要求返回最近一次插入记录时的ID(就是newid()的值)
注意:以上表结构不能改!!!(不能用set @id=newid()然后再插入到记录中)


------解决方案--------------------
select scope_identity()
------解决方案--------------------
insert into #temp (name) values ( 'fads ') 
declare @id varchar(100)
select @id=scope_identity()
return @id
------解决方案--------------------
if exists (select name from sysobjects where name= '#temp ') 
drop table #temp 
go 
create table #temp 

[ID] [uniqueidentifier] NOT NULL ,
name nvarchar(10) default( '空 ') 


go 

DECLARE @InsertID UNIQUEIDENTIFIER
SET @InsertID = NEWID()
insert into #temp (id,name) values (@InsertID, 'fads ') 
SELECT * FROM #temp where [ID]=@InsertID
------解决方案--------------------
不能用set @id=newid()然后再插入到记录中
就没有利用newid的优势,恐怕很难回答
------解决方案--------------------
OUTPUT是SQL SERVER 2005新增的关键字, SQL SERVER 2000没有.
------解决方案--------------------
你的意思是id不是自增的这种,而是newid()这种??