Katherine
Katherine

Reputation: 1

Conditional statement does not work correctly

Why I always have 'error' and none from 'if-else'?

DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());

    IF @ROZNICA = 0
    BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
    END;
    ELSE IF @ROZNICA > 0
    BEGIN
        PRINT 'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';
    END;
    ELSE
    BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
    END;
END TRY
BEGIN CATCH
    PRINT 'Error';
END CATCH;

I want something from the If Else statement to be displayed

Upvotes: 0

Views: 31

Answers (2)

Wouter
Wouter

Reputation: 2976

You cannot concatenate a date or an integer with a varchar without conversion, so you need:

 PRINT 'Między datą obecną a datą ' + cast(getdate() as varchar(10)) + ' jest ' + cast( @ROZNICA  as varchar(5))+ ' dni różnicy.';

Upvotes: 0

Ilyes
Ilyes

Reputation: 14928

Just change

'Między datą obecną a datą ' + getdate() + ' jest ' + @ROZNICA + ' dni różnicy.';

with

PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');

You get this because there is an error for casting datetime to varchar. So your code will be

DECLARE @Date DATE = '2015-01-01'

BEGIN TRY
    DECLARE @ROZNICA AS INT;
    SET @ROZNICA = DATEDIFF(day, @Date, getdate());
    IF @ROZNICA = 0
      BEGIN
        PRINT 'Data podana w parametrze jest datą bieżącą.';
      END --Remove ; from here
    ELSE IF @ROZNICA >0
      BEGIN
        PRINT concat('Między datą obecną a datą ', getdate(), ' jest ', @ROZNICA, ' dni różnicy.');
      END -- Remove ; from here
    ELSE
      BEGIN
        PRINT 'Data podana w parametrze jest większa od bieżacej.';
      END;
END TRY
  BEGIN CATCH
    PRINT 'Error';
  END CATCH;
GO

Upvotes: 1

Related Questions