Skip to content

In SQL Server, row cannot be created for models under a schema if the identity column is manually set #7523

@Benjababe

Description

@Benjababe

GORM Playground Link

go-gorm/playground#818

Description

The table I'm using is currently in a schema, set through either TableName() or schema.NamingStrategy.TablePrefix.

But if I were to try to create a row in SQL Server with it, while using a preset value for the ID column, the SET IDENTITY_INSERT statement doesn't include the schema, which causes it to fail to insert.

// Setup
db, err = gorm.Open(sqlserver.Open(dbDSN), &gorm.Config{
	NamingStrategy: schema.NamingStrategy{TablePrefix: "testing_schema."},
})
// OR
func (TestStruct) TableName() {
	return "testing_schema.test_structs"
}

// Works
workTestStruct := TestStruct{Value: "hello"}
result = DB.Create(&workTestStruct)

// Does not work
failTestStruct := TestStruct{ID: 100, Value: "there"}
result = DB.Create(&failTestStruct)
[2.397ms] [rows:1] INSERT INTO "testing_schema"."test_structs" ("created_at","updated_at","value") OUTPUT INSERTED."id" VALUES ('2025-07-21 03:01:38.323','2025-07-21 03:01:38.323','hello');
2025/07/21 02:51:53 /home/runner/work/playground/playground/main_test.go:31 mssql: Cannot find the object "test_structs" because it does not exist or you do not have permissions.; mssql: The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.

[1.908ms] [rows:0] SET IDENTITY_INSERT "test_structs" ON;INSERT INTO "testing_schema"."test_structs" ("created_at","updated_at","value","id") OUTPUT INSERTED."id" VALUES ('2025-07-21 02:51:53.448','2025-07-21 02:51:53.448','there',100);SET IDENTITY_INSERT "test_structs" OFF;

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions