我使用SQL Server。
我想编写一个存储过程,以查看是否存在questionid
和employeeid
(questionid
在表question
中,与employeeid
相同,在表employee
中),并查看它们是否在表中不存在(在表contentment
中没有重复项)。如果需要,我希望为用户提供提高。
就我而言,可能有一个重复项,但不能在同一DATE
上!
Contentment 表具有列:
employeeid, questionid, date, score
employeeid
,questionid
,date
组成主键。
所以我想要这样的东西:
1,1, 18-11-2018, null
1,1, 19-11-2018, null
不是这样的:
1,1, 18-11-2018, null
1,1, 18-11-2018, null
我已经制作了一些东西,但是它不起作用(1-1-1900是标准日期,因为它是primary key
,需要插入,score
因为用户需要这样做):
@employeeid int,
@questionid int
as
begin
if exists (select * from question where questionid = @questionid)
and exists (select * from employee where employeeid= @employeeid)
begin
insert into contentment (employeeid, questionid, date, score)
values (@employeeid, @questionid, '1-1-1900', null)
end
if (select count(*)
from contentment
where employeeid = @employeeid
and questionid = @questionid
and date = date) = 0
raiserror ('@employeeid or @questionid already existing', 16, 1)
else
raiserror ('@employeeid or @questionid are not existing', 16, 1, null)
end
答案 0 :(得分:0)
如果您要进行日期验证,则还需要提供@date。我创建了一个示例存储过程,其中提供了详细信息:
DROP PROCEDURE P_ContentmentInsert
GO
CREATE PROCEDURE P_ContentmentInsert
@employeeid int,
@questionid int,
@date DATE
AS
BEGIN
--Check if exists Employee, Question and Contentment
DECLARE @IsEmployeeExists INT=ISNULL((SELECT COUNT(1) FROM employee WHERE employeeid= @employeeid),0)
DECLARE @IsQuestionExists INT=ISNULL((SELECT COUNT(1) FROM question WHERE questionid = @questionid),0)
DECLARE @IsContentmentExists INT=ISNULL((SELECT COUNT(1) FROM contentment WHERE questionid = @questionid and employeeid= @employeeid and [date]=@date),0)
DECLARE @ErrorMessage VARCHAR(1000)=''
--If one of the validation not passed give error message
IF (@IsEmployeeExists=0 OR @IsQuestionExists=0 OR @IsContentmentExists=0)
BEGIN
IF @IsEmployeeExists=0
SET @ErrorMessage='-EmployeeId Not exists'
IF @IsQuestionExists=0
SET @ErrorMessage=@ErrorMessage+'-QuesitonId Not exists'
IF @IsContentmentExists=0
SET @ErrorMessage=@ErrorMessage+'-Contentment already exists'
RETURN
END
--If there is no problem insert it.
IF @IsEmployeeExists>0 and @IsQuestionExists>0 and @IsContentmentExists>0
BEGIN
INSERT INTO contentment (employeeid, questionid, date, score)
VALUES (@employeeid, @questionid, @date, null)
END
END