>In questa tabella c'è già un campo (id) con una chiave primaria
>ed è rappresentato da valori numerici (int).
>
>Devo creare per forza un'altra tabella?
Ciao Giovanni,
no, puoi definire un constraint UNIQUE sulla colonna nome_categoria.
Ti allego un esempio:
USE tempdb;
GO
CREATE TABLE dbo.myTable
(
myID int NOT NULL IDENTITY PRIMARY KEY,
nome_categoria varchar(11)
);
/* Aggiungo il constraint UNIQUE alla colonna
** nome_categoria
*/
ALTER TABLE dbo.myTable
ADD CONSTRAINT UN_nome_categoria UNIQUE(nome_categoria);
GO
INSERT dbo.myTable VALUES('Categoria 1');
INSERT dbo.myTable VALUES('Categoria 2');
INSERT dbo.myTable VALUES('Categoria 3');
/* Provo ad inserire una categoria già presente */
INSERT dbo.myTable VALUES('Categoria 1');
/* Output:
Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'UN_nome_categoria'.
Cannot insert duplicate key in object 'dbo.myTable'.
The statement has been terminated.
*/
SELECT *
FROM dbo.myTable;
/* Output:
myID nome_categoria
----------- --------------
1 Categoria 1
2 Categoria 2
3 Categoria 3
(3 row(s) affected)
*/
DROP TABLE dbo.myTable;
Per maggiori dettagli consulta i Books Online:
"UNIQUE Constraints"
http://msdn2.microsoft.com/en-gb/library/ms191166.aspx
Ciao!
--
Lorenzo Benaglia
Microsoft MVP - SQL Server
http://blogs.dotnethell.it/lorenzo/
http://italy.mvps.org