Search code examples
sql-servert-sqlinsert

Insert row into table with only one column, primary key and identity


Here is a table definition:

CREATE TABLE dbo.TableOnlyPK
(
    Id tinyint PRIMARY KEY IDENTITY (1, 1)
)

Now I need to insert row into that table through T-SQL statements: I've tried few solutions, but no one worked.

INSERT INTO dbo.TableOnlyPK () VALUES ()  -- not worked

Solution

  • Try:

    INSERT INTO dbo.TableOnlyPK DEFAULT VALUES
    

    You have created below table:

    CREATE TABLE dbo.TableOnlyPK
    (
        Id tinyint PRIMARY KEY IDENTITY (1, 1)
    )
    

    Each time you fire : INSERT INTO dbo.TableOnlyPK DEFAULT VALUES, you will insert one row in IDENTITY column.

    So if you execute:

    INSERT INTO dbo.TableOnlyPK DEFAULT VALUES
    INSERT INTO dbo.TableOnlyPK DEFAULT VALUES
    INSERT INTO dbo.TableOnlyPK DEFAULT VALUES
    

    It will result:

    enter image description here