Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto generate UniqueIdentifier on insert query in Sql Server? [duplicate]

Tags:

sql-server

I have a table AUDITS

CREATE TABLE AUDITS
(
    Audit_ID uniqueidentifier not null,
    LocationID char(10) 
        FOREIGN KEY REFERENCES LOCATIONS (LocationID) not null,
    DateChangement date not null,
    NomColonneChangé varchar (20) not null,
    AncienneValeur  varchar (20)  not null,
    NouvelleValeur  varchar (20) not null,

    CONSTRAINT pk_AUDIT PRIMARY KEY (Audit_ID)
)

Now I have an update trigger that inserts into this table but I want the Audit_ID to be generated automatically by SQL Server.

I thought this way is right :

if (......)
....
...
 INSERT INTO [MultiLocation].[dbo].[les_AUDITS]
       ([LocationID]
       ,[DateChangement]
       ,[NomColonneChangé]
       ,[AncienneValeur]
       ,[NouvelleValeur])
  VALUES
       (@LocationID ,
       @DateChangement ,
       @NomColonneChangée ,
       @AncienneValeur,
       @NouvelleValeur )

But it says it's impossible to insert a NULL value into Audit_ID.

How should I do it?

like image 504
bilel ben jaber Avatar asked May 26 '26 18:05

bilel ben jaber


1 Answers

When you create a table, you can create a column with uniqueidentifier data type as you did and with the default DEFAULT newid() as below

CREATE TABLE AUDITS
(
Audit_ID uniqueidentifier not null DEFAULT newid(),
LocationID char(10) FOREIGN KEY REFERENCES LOCATIONS (LocationID) not null,
DateChangement date not null,
NomColonneChangé varchar (20) not null,
AncienneValeur  varchar (20)  not null,
NouvelleValeur  varchar (20) not null,
constraint pk_AUDIT primary key(Audit_ID)
)
like image 86
Aruna Avatar answered May 28 '26 12:05

Aruna