首先,您必须创建类别查找表。您可以使用如下脚本创建它:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Categories](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[Description] [varchar](50) NOT NULL,
CONSTRAINT [PK_Categories] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [Categories] ADD CONSTRAINT [DF_Categories_Id] DEFAULT (newid()) FOR [Id]
GO
并用 4 个描述填充它:
INSERT INTO Categories ([Description])
VALUES ('Client')
INSERT INTO Categories ([Description])
VALUES ('Worker')
INSERT INTO Categories ([Description])
VALUES ('Assessor')
INSERT INTO Categories ([Description])
VALUES ('Unknown')
之后,您必须使用 Categories 表的约束创建 Persons 表:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [Persons](
[Id] [uniqueidentifier] ROWGUIDCOL NOT NULL,
[IdCategory] [uniqueidentifier] NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[FirstAddress] [varchar](250) NULL,
[SecondAddress] [varchar](250) NULL,
[ThirdAddress] [varchar](250) NULL,
[HomePhone] [varchar](50) NULL,
[MobilePhone] [varchar](50) NULL,
[Modified] [datetime] NOT NULL,
[Comment] [varchar](500) NULL,
CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [Persons] ADD CONSTRAINT [DF_Persons_Id] DEFAULT (newid()) FOR [Id]
GO
ALTER TABLE [Persons] WITH CHECK ADD CONSTRAINT [FK_Persons_Categories] FOREIGN KEY([IdCategory])
REFERENCES [Categories] ([Id])
GO
ALTER TABLE [Persons] CHECK CONSTRAINT [FK_Persons_Categories]
GO
现在你有两张桌子:)
这些脚本在 Microsoft SQL Server 上运行。
PS:最佳做法是为多个地址和多个电话做另一个表;)
要使用 SELECT 检索数据,您可以执行以下操作:
SELECT FirstName, LastName, Description AS Category
FROM Persons INNER JOIN
Categories ON Categories.Id = Persons.IdCategory
如果您使用 NUMBER 作为 ID,请更改 NUMBER 中的 IdCategory 数据类型。之后,存储过程可能如下:
CREATE PROCEDURE [AddPerson]
(
@Category varchar(50),
@FirstName varchar(50),
@LastName varchar(50),
@FirstAddress varchar(250) = NULL,
@SecondAddress varchar(250) = NULL,
@ThirdAddress varchar(250) = NULL,
@HomePhone varchar(50) = NULL,
@MobilePhone varchar(50) = NULL,
@Comment varchar(500) = NULL
)
AS BEGIN
Declare @idCategory NUMBER
Set @idCategory = SELECT Id FROM Categories WHERE Description = Category
INSERT INTO Persons ([IdCategory], [FirstName], [LastName],
[FirstAddress],
[SecondAddress],
[ThirdAddress],
[HomePhone],
[MobilePhone],
[Modified],
[Comment])
VALUES (@idCategory,
@FirstName,
@LastName,
@FirstAddress,
@SecondAddress,
@ThirdAddress,
@HomePhone,
GETDATE(),
@MobilePhone,
@Comment)
END
GO
如果这段代码包含一些错误,我很抱歉,但我是用记事本写的 :)