Michael
Michael

Reputation: 13636

How to add row to a SQL Server table with uniqueidentifier type column?

I need to add a row to a SQL Server table called Customers.

Here is the table design:

enter image description here

Here how I try to add a row to the table above:

INSERT INTO Customers (Id, Name) 
VALUES (1, 'test');

But I get this error:

Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with uniqueidentifier

As you can see the ID column of type uniqueidentifier. How do I add a uniqueidentifier to the column above?

Upvotes: 1

Views: 3912

Answers (2)

Tomas
Tomas

Reputation: 755

The uniqueidentifier data type stores 16-byte binary values that operate as globally unique identifiers (GUIDs).

Example using:

insert into customers values('7E3E3BC1-9B15-473C-A45A-46D89689156C', 'Tomas')
insert into customers values(newid(), 'Tomas')

See more details: https://technet.microsoft.com/en-US/library/ms190215(v=sql.105).aspx

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1271031

Use newid():

INSERT INTO Customers(Id, Name) VALUES (newid(), 1);

Note that this would often be done using a default value:

create table customers (
    id uniqueidentifier default newid(),
    . . .
);

For various technical reasons, it is not recommended to make the uniqueidentifier column a primary key -- although you can get around some of the problems using newsequentialid().. Instead, make it a unique key and have another key (typically an identity() column) as the primary key.

Upvotes: 3

Related Questions