为什么查询没有返回结果

时间:2021-03-19 05:01:55

标签: sql sql-server tsql stored-procedures

我正在尝试编写 SQL 查询来满足以下要求。表、列和值的所有命名约定都是正确的。但是我的查询没有返回任何内容。

  • 检查 SpecializationCode 表中是否存在 Specialization。如果不存在,将SpecializationCodeSpecializationName插入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

1 个答案:

答案 0 :(得分:-1)

Return -1 块中的 SELECT 1 / 0 AS Error; 替换为 TRYReturn -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