forked from microsoft/go-mssqldb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lastinsertid_example_test.go
60 lines (51 loc) · 1.63 KB
/
lastinsertid_example_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//go:build go1.10
// +build go1.10
package mssql_test
import (
"database/sql"
"log"
)
// This example shows the usage of Connector type
func ExampleLastInsertId() {
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
// Create table
_, err = db.Exec("create table foo (bar int identity, baz int unique);")
if err != nil {
log.Fatal(err)
}
defer db.Exec("if object_id('foo', 'U') is not null drop table foo;")
// Attempt to retrieve scope identity using LastInsertId
res, err := db.Exec("insert into foo (baz) values (1)")
if err != nil {
log.Fatal(err)
}
n, err := res.LastInsertId()
if err != nil {
log.Print(err)
// Gets error: LastInsertId is not supported. Please use the OUTPUT clause or add `select ID = convert(bigint, SCOPE_IDENTITY())` to the end of your query.
}
log.Printf("LastInsertId: %d\n", n)
// Retrieve scope identity by adding 'select ID = convert(bigint, SCOPE_IDENTITY())' to the end of the query
rows, err := db.Query("insert into foo (baz) values (10); select ID = convert(bigint, SCOPE_IDENTITY())")
if err != nil {
log.Fatal(err)
}
defer rows.Close()
var lastInsertId1 int64
for rows.Next() {
rows.Scan(&lastInsertId1)
log.Printf("LastInsertId from SCOPE_IDENTITY(): %d\n", lastInsertId1)
}
// Retrieve scope identity by 'output inserted``
var lastInsertId2 int64
err = db.QueryRow("insert into foo (baz) output inserted.bar values (100)").Scan(&lastInsertId2)
if err != nil {
log.Fatal(err)
}
log.Printf("LastInsertId from output inserted: %d\n", lastInsertId2)
}