Auto fill insert date and unique id (PK) columns in SQL Server

jgwigjjp  于 2023-03-22  发布在  SQL Server
关注(0)|答案(1)|浏览(120)

I have created the table but the query I am using to insert the data does not match the table structure since I am expecting Date_Inserted and Unique_ID to auto populate and I do not have data to fill these columns. Hence, I m getting this error: Column name or number of supplied values does not match table definition.

USE [db_db]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[my_table](
    [V01_V] [real] NULL,
    [V02_V] [real] NULL,
    [V03_V] [real] NULL,
    [V04_V] [real] NULL,
    [V05_V] [real] NULL
    [Date_Inserted] [datetime] NOT NULL,
    [Unique_ID] [int] IDENTITY(1,1) NOT NULL,
    CONSTRAINT [PK_row_id] PRIMARY KEY CLUSTERED
(
    [Unique_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

insert into dbo.my_table
Select Distinct 
  mot.V01_V,
  mot.V02_V,
  mot.V03_V,
  mot.V04_V,
  mot.V05_V
  --Date_Inserted (exist in my table structure but I do not have data to fill these)
  --Unique_ID (exist in my table structure but I do not have data to fill these)

From dbo.my_other _table mot
fkaflof6

fkaflof61#

You can add a default constraint to your column like this:

CREATE TABLE [dbo].[my_table](
[V01_V] [real] NULL,
[V02_V] [real] NULL,
[V03_V] [real] NULL,
[V04_V] [real] NULL,
[V05_V] [real] NULL
[Date_Inserted] [datetime] NOT NULL DEFAULT GETDATE(),
[Unique_ID] [int] IDENTITY(1,1) NOT NULL,
CONSTRAINT [PK_row_id] PRIMARY KEY CLUSTERED
(
    [Unique_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

相关问题