SQL - 将IF条件添加到我的存储过程

时间:2013-12-19 08:05:42

标签: sql-server

我有一个存储过程,其中增加 sub_days 每日

我想添加条件

  

如果 sub_days = 30 ,则 sub_months = sub_months + 1 ,   的 sub_days = 0

如何将此条件添加到我的存储过程?

我的SP:

    ALTER PROCEDURE [dbo].[Update_Users_With_Month] 
     @ID bigint


    AS
    BEGIN

       update Subscribers_Profile 
       set Sub_Updated = GETDATE() , sub_days = sub_days+1
       where sub_ID = @ID


**add condition here**

    END

4 个答案:

答案 0 :(得分:3)

这样的东西?

ALTER PROCEDURE [dbo].[Update_Users_With_Month] 
@ID bigint

AS
BEGIN

   update Subscribers_Profile 
   set Sub_Updated = GETDATE()
      , sub_days = CASE WHEN sub_days+1 >= 30 THEN 0 ELSE sub_days+1 END
      , sub_months = CASE WHEN sub_days+1 >= 30 THEN sub_months+1 ELSE sub_months END
   where sub_ID = @ID

END

如果你在sub_months中有NULL,你可以在这种情况下使用ISNULL,如:

... THEN ISNULL(sub_months,0)+1 ELSE sub_months END ...

答案 1 :(得分:0)

ALTER PROCEDURE [dbo].[Update_Users_With_Month] @ID bigint AS BEGIN
UPDATE Subscribers_Profile
SET Sub_Updated = GETDATE() ,
                  sub_days = sub_days+1
WHERE sub_ID = @ID 

  DECLARE  @sub_days  INT;
  SET @sub_days  = (SELECT sub_days FROM dbo.Subscribers_Profile WHERE sub_ID = @ID);
IF @sub_days =30 

BEGIN
  UPDATE Subscribers_Profile
  SET sub_months = sub_months +1 ,
      sub_days=0 WHERE sub_ID = @ID ;

 END 

ELSE 


END

答案 2 :(得分:0)

尝试

您可能会根据您的示例代码查看

 ALTER PROCEDURE [dbo].[Update_Users_With_Month] 
 @ID bigint
AS
BEGIN
Declare @Sub_Days int
Declare @sub_months int

SELECT @Sub_Days = sub_days + 1, @sub_months = sub_months
FROM Subscribers_Profile
WHERE sub_ID = @ID

If @Sub_Days >= 30
BEGIN
    SET @Sub_Days = 0;
    SET @sub_months = @sub_months + 1
END

UPDATE Subscribers_Profile 
    SET Sub_Updated = GETDATE(),
    sub_months = @sub_months,
    sub_days=@Sub_Days
WHERE sub_ID = @ID

END

答案 3 :(得分:0)

试试这个。

ALTER PROCEDURE [dbo].[Update_Users_With_Month] @ID bigint AS BEGIN 
 SET Sub_Updated = GETDATE() ,
                 sub_days = sub_days+1
  WHERE sub_ID = @ID 

  DECLARE  @sub_days  INT;
    SET @sub_days  = (SELECT sub_days FROM dbo.Subscribers_Profile WHERE sub_ID = @ID);
     IF @sub_days =30 

  BEGIN
      UPDATE Subscribers_Profile
      SET sub_months = sub_months +1 ,
      sub_days=0 WHERE sub_ID = @ID ;

   END 

  ELSE 


    END