Search code examples
pythonsql-serversqlalchemypymssql

How to define start value for ID column in SQLAlchemy for SQLServer?


I interfacing SQLAlchemy between Flask and SQLServer.

I have an ID column which I would like to start from 10000. I couldn't find the answer.

Below is the SQL code, I am trying to convert to SQLAlchemy.

Please let me know.

Thx

create TABLE [dbo].[Product](
    [ID] [int] IDENTITY(**10000**,1) NOT NULL,
    [Name] [varchar](200) NOT NULL,
    [Description] [varchar](500) NULL,
    [Brand] [varchar](500) NOT NULL,
    [Price] [real] NOT NULL,
    [Qty] [int] NOT NULL,
    [ProductFilenamePrefix] [varchar](200) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
UNIQUE NONCLUSTERED 
(
    [Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Solution

  • You'll need to do some changes after SQLAlchemy creates the table, as shown in the links above for MySQL, but with SQL Server.

    from sqlalchemy import event
    from sqlalchemy import DDL
    event.listen(
        Article.__table__,
        "after_create",
        DDL("DBCC checkident (%(table)s, reseed, 9999)")
    )
    

    This will make the next record inserted start at an identity value of 10000. Good luck.