1

I want to insert new records into a table called [dbo].[Local] that has these columns:

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

And the primary key called [id] is key clustered as:

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

The insert command is like shown below. But how can I set a value for the [id] column because I get an error when I try to enter the value in the [id] column. How can I insert value to this field automatically?

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

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
MarkP
  • 23
  • 2
  • 2
  • 5
  • What error do you get? – Alejandro Nov 07 '17 at 15:28
  • The value '00000000-0000-0000-000-00000000000' is just an example in the query. What i actually want is to enter a random value in the uniqueidentifier automatically each time i add a new record with an insert into statement. – MarkP Nov 07 '17 at 15:29
  • Possible duplicate of [How to generate and manually insert a uniqueidentifier in sql server?](https://stackoverflow.com/questions/17274276/how-to-generate-and-manually-insert-a-uniqueidentifier-in-sql-server) – Alejandro Nov 07 '17 at 15:30
  • Select newid(), it will return random for you – Edward N Nov 07 '17 at 15:30

2 Answers2

3

You need to cast the value you want to insert to UNIQUEIDENTIFIER-type:

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'
    )

For inserting a new random UNIQUEIDENTIFIER you can use NEWID():

INSERT INTO [dbo].[Local]
    (         
    [id],
    [Component],
    [Language],
    [IsText],
    [key],
    [value])
VALUES
    (
     NEWID(), 
     'Transport.Web',
     'en',
     1,
     'ResourceTypeEmployee',
     'TypeOffice'
    )
MatSnow
  • 7,357
  • 3
  • 19
  • 31
0

the insert select face :

INSERT INTO foo 
([UNIQUEIDENTIFIER_col] ,[col2] , [...]) 
select NEWID() , [bar.selected_col1] , [...] from bar 
where (condition) 
Farhad Shekari
  • 2,245
  • 1
  • 14
  • 12