如何在SQL Server 2012中创建选择,然后更新存储过程

时间:2014-08-18 11:21:12

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

我尝试创建一个运行select查询并提取id(变量)的存储过程,然后对该id执行更新查询。任何帮助将不胜感激。

这就是我所拥有的:

CREATE PROCEDURE dbo.Lead_usp_getLead
    @LeadId int output
AS

   SELECT TOP 1  
       Leadid, LeadInitials, LeadFirstName, LeadSurname, 
       LeadHomeTelephoneNumber, LeadWorkTelephoneNumber,
       LeadCellularNumber, LeadEMailAddress, IsLocked, uploadedDate
   FROM 
       dbo.Lead
   WHERE 
       IsLocked = 'False'
   ORDER BY 
       uploadedDate;

   UPDATE dbo.Lead
   SET IsLocked = 'TRUE'
   WHERE LeadId = @LeadId

   DECLARE @leadid int

   EXEC dbo.Lead_usp_getLead @leadId;

3 个答案:

答案 0 :(得分:0)

你可以把它们组合起来。无需进行两次查询:

with toupdate as (
      SELECT TOP 1 l.*
      FROM dbo.Lead l
      WHERE l.IsLocked = 'False'
      ORDER BY l.uploadedDate
     )
Update toupdate
    SET IsLocked = 'TRUE';

答案 1 :(得分:0)

不要理解你的最终结果,但是:

UPDATE dbo.Lead SET IsLocked = 'TRUE'
WHERE Leadid = (SELECT TOP 1 Leadid FROM dbo.Lead WHERE IsLocked = 'False')

答案 2 :(得分:0)

如果创建存储过程的唯一目的是运行select查询并提取id(变量)并且不包含其他复杂的业务逻辑..那么你应该编写一个函数,而不是:

IF OBJECT_ID (N'dbo.Lead_fn_getLead', N'FN') IS NOT NULL
    DROP FUNCTION dbo.Lead_fn_getLead;
GO

CREATE FUNCTION dbo.Lead_fn_getLead (@LeadId int)
RETURNS int
AS
BEGIN 
   DECLARE @varLeadId int

   SELECT TOP 1  @varLeadId =  
       Leadid
   FROM 
       dbo.Lead
   WHERE 
       IsLocked = 'False'
   ORDER BY 
       uploadedDate;

 RETURN(@varLeadId);
END;
Go

然后写为更新表:

DECLARE @leadid int
SET @leadid = 1

UPDATE dbo.Lead
SET IsLocked = 'TRUE'
WHERE LeadId = (Select dbo.Lead_fn_getLead(@leadid))

Go

Check demo here..