3

After an insert, I need to know the ID from the row, how can I do that?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
xaver23
  • 1,301
  • 3
  • 12
  • 14

2 Answers2

2

According to the Dataset#insert documentation, the return value for insert() is usually the primary key of the inserted row, but it depends which adapter you're using.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Greg Campbell
  • 15,182
  • 3
  • 44
  • 45
1

I tried the same with SQL-Server and a uniqueidentifier, but without success. The uniqueidentifier is not returned.

Extract from my Definition:

CREATE TABLE [dbo].[MyTable](
     [ID] [uniqueidentifier] NOT NULL,
     [Data] [nvarchar](255) NULL
)
ALTER TABLE [dbo].[MyTable] ADD  DEFAULT (newid()) FOR [ID]

When I insert with Sequel:

DB[:MyTable].insert( :Data => 'data' )

the dataset is added with a uniqueidentifier, but the return code if Dataset#insert is nil.

With

DB[:MyTable].insert(:ID => Sequel.function(:newid),  :Data => 'data' )

you get the same result.

I tried

key = Sequel.function(:ID)
DB[:MyTable].insert(:ID => key,  :Data => 'data' )

but 'key' is only the function call, not the value. With Sequel.function(:ID).f you get an "Invalid column name ID'."-error

But if you use a Model, the you get the uniqueidentifier:

class MyTable < Sequel::Model(:MyTable); end 
entry = MyTable.create(:Data => 'data')
$uniqueidentifier = entry[:ID]
knut
  • 27,320
  • 6
  • 84
  • 112