WITH ValidPatients AS (
    SELECT
        A.PatientCode,
        A.ExamFeeitem_Code,
        A.ExamDatetime,
        A.ExamDoctor,
        A.InputDoctor,
        A.ExamDesc,
        A.ExamSummary,
        A.ExamPositive,
        A.ImageTitle,
        A.TransfTertarget,
        A.ReportFile_PDF
    FROM
        pacs.DICOMSERVER.dbo.PEIS_PacsResult A
    WHERE
        A.ExamDatetime IS NOT NULL
        AND A.PatientCode IS NOT NULL
        AND ISNUMERIC(A.PatientCode) = 1  -- Filter for numeric PatientCode
        AND LEN(A.PatientCode) <= 19  -- Ensure length is within bigint range
        AND A.PatientCode NOT LIKE '%[^0-9]%'  -- Ensure no non-digit characters
        AND EXISTS (SELECT 1 FROM Enrollment_Patient WHERE ID = CAST(A.PatientCode AS bigint))
)
INSERT INTO Report (EID, ReportNo, ReportTime, Reporter, Examer, Description, Summary, Positive, Title, Class, ReportImage, InTime)
SELECT
    CAST(PatientCode AS bigint) AS EID,
    ExamFeeitem_Code AS ReportNo,
    ExamDatetime AS ReportTime,
    ExamDoctor AS Reporter,
    InputDoctor AS Examer,
    ExamDesc AS Description,
    ExamSummary AS Summary,
    ExamPositive AS Positive,
    ImageTitle AS Title,
    TransfTertarget AS Class,
    ReportFile_PDF AS ReportImage,
    GETDATE() AS InTime
FROM
    ValidPatients;
