Julio Arriaga
Julio Arriaga

Reputation: 970

I can't use a variable in a SQL query Msg 137 Must declare the scalar variable

I want to create a query that calculates some indicators within a time range defined by some variables, but I'm not sure if it is possible to use the variables the way I'm intending.

I get the following error:

Msg 137, Level 15, State 2, Line 7
Must declare the scalar variable "@vDiai".

The column TPO_CFecha is of type int.

I don't know what I'm doing wrong:

DECLARE @vDiai INT;
DECLARE @vDiaf INT;
SET @vDiai = 20171030;
SET @vDiaf = 20181030;

USE DBDMS
GO

SELECT 
    CAST(100 * Baja / (HeadcountBruto / Dias) AS decimal(20, 5)) 
FROM 
    (SELECT 
         SUM(ROT_IBAJA) AS Baja,
         COUNT(DISTINCT R.TPO_KFecha) AS Dias,
         SUM(ROT_IHCOUNT) AS HeadcountBruto
     FROM 
         TH_Rotacion R
     INNER JOIN 
         TD_Tiempo T ON R.TPO_KFECHA=T.TPO_KFecha
     WHERE 
         T.TPO_CFecha >= @vDiai
         AND T.TPO_CFecha <= @vDiaf) T
go

SELECT DATA_TYPE 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE 
     TABLE_NAME = 'TD_Tiempo' AND 
     COLUMN_NAME = 'TPO_CFecha'
go

Upvotes: 0

Views: 1594

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269613

The GO breaks up your script. Just move it or remove it:

USE DBDMS
GO

DECLARE @vDiai INT;
DECLARE @vDiaf INT;
SET @vDiai = 20171030;
SET @vDiaf = 20181030;

SELECT CAST(100*Baja/(HeadcountBruto/Dias) AS decimal(20,5)) 
FROM (SELECT SUM(ROT_IBAJA) AS Baja,
             COUNT(DISTINCT R.TPO_KFecha) AS Dias,
             SUM(ROT_IHCOUNT) AS HeadcountBruto
      FROM TH_Rotacion R INNER JOIN
           TD_Tiempo T
           ON R.TPO_KFECHA = T.TPO_KFecha
      WHERE T.TPO_CFecha >= @vDiai AND T.TPO_CFecha <= @vDiaf
     ) T;

Upvotes: 8

Related Questions