sql-servererror-handlingscalar

Must declare a scalar variable


I was creating a column that will give a me random number but I was getting some errors.

CREATE TABLE tblBookInfo
(
AccessionNumber NVARCHAR(MAX)
 RandomNumber NVARCHAR(10);
 AccNo NVARCHAR(MAX)
 @Upper INT;
 @Lower INT

SET @Lower = 1
SET @Upper = 9999

Select @RandomNumber = Round (((@Upper - @Lower -1)* RAND() + @Lower), 0)

SET @AccNo = 'LIBBOOKS' + RandomNumber
SELECT @AccNo

Set AccessionNumber = AccNo
)

ERRORS:

Incorrect syntax near 'RandomNumber'.
Must declare the scalar variable "@Lower".
Must declare the scalar variable "@Upper".
Must declare the scalar variable "@Upper".
Must declare the scalar variable "@AccNo".
Must declare the scalar variable "@AccNo".

tHank you for your help :D


Solution

  • Its not very clear what you are trying to accomplish, but here is my interpretation of your code in the correct T-SQL syntax. I'm not prepared to guess what you're trying to do below that.

    CREATE TABLE tblBookInfo 
    (   
        AccessionNumber NVARCHAR(MAX),
        RandomNumber NVARCHAR(10), 
        AccNo NVARCHAR(MAX) 
    )
    DECLARE @Upper          INT, 
            @Lower          INT,
            @RandomNumber   INT
    
    SET @Lower = 1 SET @Upper = 9999
    
    SELECT @RandomNumber = Round (((@Upper - @Lower -1)* RAND() + @Lower), 0)
    
    SELECT @RandomNumber