我正在尝试编写一个存储过程,根据患者姓名检查patientID是否存在。
if exists (select pt.Id from dbo.Patients as pt where ltrim(RTRIM(pt.FirstName))=pt.FirstName and LTRIM(rtrim(pt.LastName))=pt.LastName)
begin
pID=select pt.Id from dbo.Patients as pt where ltrim(RTRIM(pt.FirstName))=pt.FirstName and LTRIM(rtrim(pt.LastName))=pt.LastName
else
--increment PatentID
有没有办法不做两次选择查询
答案 0 :(得分:1)
pID = select MAX(pt.Id) from dbo.Patients as pt where trim(RTRIM(pt.FirstName))=pt.FirstName and LTRIM(rtrim(pt.LastName))=pt.LastName;
IF @pID IS NULL
--Increment
答案 1 :(得分:1)
只需设置变量,然后检查它是否为空。
SELECT @pID = pt.Id from dbo.Patients as pt
WHERE ltrim(RTRIM(pt.FirstName))=pt.FirstName
AND LTRIM(rtrim(pt.LastName))=pt.LastName)
IF (@pID IS NULL)
BEGIN
--increment PatientID
SELECT @pID = MAX(Id) + 1 FROM dbo.Patients
-- insert new record
END