Insert a uniqueidentifier field on SQL Server


Written on February 2, 2008 – 12:33 am | by André Gomes

The type uniqueidentifier is the way to make an autoincrement field on a table, using SQL Server.

In this post i will demonstrate how you can autoincrement that field when you make an insert on the table, for example.

Now, creates a simple table:

CREATE TABLE Users(

Id uniqueidentifier,

Name nvarchar(50),

Email nvarchar(50),

)

To insert an element here, in Id field you should use the NewId().
Do the following code:

INSERT INTO Users (Id, Name, Email)
           VALUES (NewId(), 'Andre', 'aslgomesATgmailDOTcom')


Veja também:

Tags: , , ,

  1. 3 Responses to “Insert a uniqueidentifier field on SQL Server”

  2. By Contente on Feb 2, 2008 | Reply

    obrigado pela dica!
    da smpr jeito aprender umas coisinhas po trab d bd sem ter k tar a investigar!

    abraco

  3. By David on Feb 2, 2008 | Reply

    Na realidade o tipo de dados uniqueidentifier permite armazenar guids, o que é um pouco diferente de um campo que incremente automaticamente, e o newid() cria um novo guid.

    O que tu queres deve ser um identity, não? Com o teu exemplo:

    create table Users(id int identity(1,1), Name nvarchar(50), Email nvarchar(50))

    insert into Users values (’Andre’, ‘aslgomesATgmailDOTcom’)

    identity(N,M) significa incrementos de M unidades a começar em N.

    T-SQL Reference: http://msdn2.microsoft.com/en-us/library/ms189826.aspx

  1. 1 Trackback(s)

  2. Feb 2, 2008: Insert autonumber field on SQL Server « André Gomes

Post a Comment