forked from denisenkom/go-mssqldb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tvp_example_test.go
100 lines (85 loc) · 2.16 KB
/
tvp_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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//go:build go1.10
// +build go1.10
package mssql_test
import (
"database/sql"
"fmt"
"log"
mssql "github.com/denisenkom/go-mssqldb"
)
// This example shows how to use tvp type
func ExampleTVP() {
const (
createTable = "CREATE TABLE Location (Name VARCHAR(50), CostRate INT, Availability BIT, ModifiedDate DATETIME2)"
createTVP = `CREATE TYPE LocationTableType AS TABLE
(LocationName VARCHAR(50),
CostRate INT)`
dropTVP = "IF type_id('LocationTableType') IS NOT NULL DROP TYPE LocationTableType"
createProc = `CREATE PROCEDURE dbo.usp_InsertProductionLocation
@TVP LocationTableType READONLY
AS
SET NOCOUNT ON
INSERT INTO Location
(
Name,
CostRate,
Availability,
ModifiedDate)
SELECT *, 0,GETDATE()
FROM @TVP`
dropProc = "IF OBJECT_ID('dbo.usp_InsertProductionLocation', 'P') IS NOT NULL DROP PROCEDURE dbo.usp_InsertProductionLocation"
execTvp = "exec dbo.usp_InsertProductionLocation @TVP;"
)
type LocationTableTvp struct {
LocationName string
LocationCountry string `tvp:"-"`
CostRate int64
Currency string `json:"-"`
}
connString := makeConnURL().String()
db, err := sql.Open("sqlserver", connString)
if err != nil {
log.Fatal("Open connection failed:", err.Error())
}
defer db.Close()
_, err = db.Exec(createTable)
if err != nil {
log.Fatal(err)
}
_, err = db.Exec(createTVP)
if err != nil {
log.Fatal(err)
}
defer db.Exec(dropTVP)
_, err = db.Exec(createProc)
if err != nil {
log.Fatal(err)
}
defer db.Exec(dropProc)
locationTableTypeData := []LocationTableTvp{
{
LocationName: "Alberta",
LocationCountry: "Canada",
CostRate: 0,
Currency: "CAD",
},
{
LocationName: "British Columbia",
LocationCountry: "Canada",
CostRate: 1,
Currency: "CAD",
},
}
tvpType := mssql.TVP{
TypeName: "LocationTableType",
Value: locationTableTypeData,
}
_, err = db.Exec(execTvp, sql.Named("TVP", tvpType))
if err != nil {
log.Fatal(err)
} else {
for _, locationData := range locationTableTypeData {
fmt.Printf("Data for location %s, %s has been inserted.\n", locationData.LocationName, locationData.LocationCountry)
}
}
}