我正在尝试编写 SQL 查询来满足以下要求。表、列和值的所有命名约定都是正确的。但是我的查询没有返回任何内容。
SpecializationCode
表中是否存在 Specialization
。如果不存在,将SpecializationCode
和SpecializationName
插入Specialization
表Doctor
表DoctorID
和给定的 SpecializationCode
插入到 DoctorSpecialization
表中,SpecializationDate
作为当前日期CREATE PROCEDURE usp_AddDoctorDetails
(@DoctorName VARCHAR(25),
@SpecializationCode CHAR(3),
@SpecializationName VARCHAR(20))
AS
BEGIN
DECLARE @DoctorID INT
SELECT @DoctorID = DoctorID
FROM Doctor
WHERE DoctorName = @DoctorName
BEGIN TRY
IF NOT EXISTS (SELECT SpecializationCode FROM Specialization
WHERE @SpecializationCode = SpecializationCode)
BEGIN
INSERT INTO Specialization (SpecializationCode, SpecializationName)
VALUES (@SpecializationCode, @SpecializationName)
INSERT INTO Doctor (DoctorID, DoctorName)
VALUES (@DoctorID, @DoctorName)
INSERT INTO DoctorSpecialization (DoctorID, SpecializationCode, SpecializationDate)
VALUES (@DoctorID, @SpecializationCode, GETDATE())
RETURN -1
END
END TRY
BEGIN CATCH
RETURN -99
END CATCH
END
GO
答案 0 :(得分:-1)
将 Return -1
块中的 SELECT 1 / 0 AS Error;
替换为 TRY
将 Return -99
替换为
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
位于 CATCH
块
仅使用 TRY CATCH 块进行更改后,您的程序看起来像这样
BEGIN try
IF NOT EXISTS (SELECT specializationcode
FROM specialization
WHERE @SpecializationCode = specializationcode)
BEGIN
INSERT INTO specialization
(specializationcode,
specializationname)
VALUES (@SpecializationCode,
@SpecializationName)
INSERT INTO doctor
(doctorid,
doctorname)
VALUES (@DoctorID,
@DoctorName)
INSERT INTO doctorspecialization
(doctorid,
specializationcode,
specializationdate)
VALUES (@DoctorID,
@SpecializationCode,
Getdate())
SELECT
1 / 0 AS Error;
END
END try
BEGIN catch
SELECT
ERROR_LINE() AS ErrorLine,
ERROR_MESSAGE() AS ErrorMessage;
END catch