SQL Server how to get inserted sequential uniqueidentifier

camsedfj  于 2023-10-15  发布在  其他
关注(0)|答案(3)|浏览(105)

my table looks like this:

create table foos(
id uniqueidentifier primary KEY DEFAULT (newsequentialid()),
..
)

so the id is sequentially generated automatically, I'm not setting it

how do I get it's value after the insert ? (with identity I was doing insert ... select @@identity )

u5rb5r59

u5rb5r591#

Returning the NewSequentialID() after Insert using the Output Clause

The basic idea:

create table foos(id uniqueidentifier primary KEY DEFAULT (newsequentialid()))

declare @Ids table(id uniqueidentifier)

insert foos
output inserted.id into @Ids
default values

select *
from @Ids
shyt4zoc

shyt4zoc2#

Is possible to use one auxiliar table, you can think about some temp table... This is one possible solution:

DECLARE @NewId UNIQUEIDENTIFIER
DECLARE @MyTableOutput TABLE
(
    AuxId int NOT NULL
    ,NewID UNIQUEIDENTIFIER DEFAULT NEWSEQUENTIALID()
)
INSERT INTO @MyTableOutput (AuxId) VALUES (1)
SELECT @NewId = NewID FROM @MyTableOutput
DELETE FROM @MyTableOutput

So you get your NewId to use in your INSERT, will work as one GEN_ID()

INSERT INTO MyTableFoos(MyId, MyValue...) VALUES (@NewId,'MyValue'...)

Your DEFAULT NEWSEQUENTIALID() will be on your TempTable, and your real table let without DEFAULT to your UNIQUEIDENTIFIER

fzwojiic

fzwojiic3#

You would use the other data that got inserted with the id to select it out again. So where you have the .. you would have:

SELECT id
WHERE ..

which would return the id

相关问题