使用uniqueidentifier列插入记录

时间:2017-11-07 15:04:10

标签: sql-server identifier

我想将新记录插入名为[dbo].[Local]的表中,该表包含以下列:

[id] [uniqueidentifier] NOT NULL,
[Component] [varchar](100) NULL,
[Language] [varchar](10) NULL,
[IsText] [bit] NULL,
[key] [varchar](100) NULL,
[value] [varchar](max) NULL,

名为[id]的主键是密钥聚类为:

[id] ASC) 
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
      IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

insert命令如下所示。但是,如何为[id]列设置值,因为当我尝试在[id]列中输入值时出现错误。 如何自动将值插入此字段?

INSERT INTO [dbo].[Local] ([id], [Component], [Language], [IsText], [key],[value])
VALUES (00000000-0000-0000-000-00000000000, 
        'Transport.Web', 'en', 1, 'ResourceTypeEmployee', 'TypeOffice')
GO

由于

2 个答案:

答案 0 :(得分:1)

您需要将要插入的值转换为UNIQUEIDENTIFIER - 输入:

INSERT INTO [dbo].[Local]
    (         
    [id],
    [Component],
    [Language],
    [IsText],
    [key],
    [value])
VALUES
    (
     CAST('00000000-0000-0000-0000-000000000000' AS UNIQUEIDENTIFIER), 
     'Transport.Web',
     'en',
     1,
     'ResourceTypeEmployee',
     'TypeOffice'
    )

要插入新的随机UNIQUEIDENTIFIER,您可以使用NEWID()

INSERT INTO [dbo].[Local]
    (         
    [id],
    [Component],
    [Language],
    [IsText],
    [key],
    [value])
VALUES
    (
     NEWID(), 
     'Transport.Web',
     'en',
     1,
     'ResourceTypeEmployee',
     'TypeOffice'
    )

答案 1 :(得分:0)

插入选择面:

INSERT INTO foo 
([UNIQUEIDENTIFIER_col] ,[col2] , [...]) 
select NEWID() , [bar.selected_col1] , [...] from bar 
where (condition)