缺少表定义的SQL条件

时间:2014-01-29 16:18:21

标签: c# asp.net sql sql-server

我想知道在我的表定义中添加什么条件,以便在这些字段doctorId,dateApt,hourApt用于相同的日期和小时以及doctorId时不允许创建新行。

ex:  aptId  ClientId  doctorId  dateApt     TimeApt  IsAvaiable
     1      Null      1         2014/01/29  09:00    True
     2      Null      1         2014/01/29  09:00    True    <== not allowing this
     3      Null      1         2014/01/29  10:00    True    <== ok bc not same hour and date
     4      Null      2         2014/01/29  09:00    True    <== ok not same doctorId

这是表格定义。

CREATE TABLE [dbo].[Appointement] (
    [aptId]       INT      IDENTITY (1, 1) NOT NULL,
    [clientId]    INT      NULL,
    [doctorId]    INT      NOT NULL,
    [dateApt]     DATE     NOT NULL,
    [hourApt]     TIME (7) NOT NULL,
    [IsAvailable] BIT      NULL,
    PRIMARY KEY CLUSTERED ([rdvId] ASC),
    CONSTRAINT [fk_doctorID] FOREIGN KEY ([doctorId]) REFERENCES [dbo].[Doctor] ([Id]),
    CONSTRAINT [fk_clientID] FOREIGN KEY ([clientId]) REFERENCES [dbo].[User] ([Id_user])
);

由于

4 个答案:

答案 0 :(得分:3)

在这些列上添加唯一约束:

ALTER TABLE dbo.Appointement
  ADD CONSTRAINT uAppt UNIQUE (doctorId, dateApt, hourAp)

或者在创建表时添加它:

CREATE TABLE [dbo].[Appointement] (
     [aptId]       INT      IDENTITY (1, 1) NOT NULL,
     [clientId]    INT      NULL,
     [doctorId]   INT      NOT NULL,
     [dateApt]   DATE     NOT NULL,
     [hourApt]  TIME (7) NOT NULL,
     [IsAvailable] BIT      NULL,
     PRIMARY KEY CLUSTERED ([rdvId] ASC),
     CONSTRAINT [fk_doctorID] FOREIGN KEY ([doctorId]) REFERENCES [dbo].[Doctor] ([Id]),
     CONSTRAINT [fk_clientID] FOREIGN KEY ([clientId]) REFERENCES [dbo].[User] ([Id_user]),
     CONSTRAINT uAppt UNIQUE (doctorId, dateApt, hourAp)
 );

答案 1 :(得分:1)

我添加了这一行      CONSTRAINT uniqueAPT UNIQUE(doctorId,dateApt,hourApt)

答案 2 :(得分:0)

我认为你要找的是unique constraint

CONSTRAINT [UQ_DoctorID_DateApt_HourApt] UNIQUE NONCLUSTERED
(
    [DoctorId], [DateApt], [HoursApt]
)
) ON [PRIMARY]

(这是CREATE TABLE语句的一部分的语法)

答案 3 :(得分:0)

这是一个忽略重复约会的INSTEAD OF触发器:

在Appointement上创建触发器ignoreDups 而不是插入 如   声明@cId int   设置@cid =(从插入中选择clientId)   声明@did int   设置@did =(从插入中选择doctorId)   声明@dApt日期   设置@dApt =(从插入中选择dateApt)   宣布@hApt时间   设置@hApt =(从插入中选择hourApt)   声明@avail位   设置@avail =(从插入中选择IsAvailable)

if(从Appointement中选择count(*)       其中@dApt = dateApt和@hApt = hourApt和doctorid = @ did)= 0           插入Appointement(clientId,doctorid,dateApt,hourApt,IsAvailable)值(@ cid,@ did,@ dApt,@ hApt,@ avail)

这是sqlfidle