为内部(如果存在)sql存储过程中的变量赋值

时间:2014-02-06 17:05:40

标签: sql sql-server sql-server-2008 stored-procedures

我正在尝试编写一个存储过程,根据患者姓名检查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  

有没有办法不做两次选择查询

2 个答案:

答案 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