You must Sign In to post a response.
  • Category: SQL Server

    Must declare the scalar variable - SQL Server

    The attached query throws the below error message. how to resolve the error message

    DECLARE @i1 INT
    ,@a INT
    ,@b VARCHAR(10)
    ,@c VARCHAR(100)

    SET @i1 = 1
    SET @b = '@i' + '1'

    SET @c = 'select @a=@i' + '1'
    exec (@c)

    Must declare the scalar variable "@i1".
  • #761248
    hi
    the issue is with the statement
    SET @c = 'select @a=@i' + '1'

    print @c will show the output as
    "select @a=@i1'

    i didnt get what you are trying to do here. so please correct the data in @c

    Do Good... Enjoy your life.....

  • #761250
    Try this. am not sure whether u want the same


    SET @c = 'select '+CONVERT(varchar(50), @i1)
    print @c
    exec (@c)

    Do Good... Enjoy your life.....

  • #761251
    Hi
    sivs

    You can try this Sql Query


    DECLARE @i1 INT
    DECLARE @a INT
    DECLARE @b VARCHAR(10)
    DECLARE @c VARCHAR(100)
    SET @i1 = 2
    SET @b = '@i' + '1'
    SET @c = 'select cast(@i1 as varchar(20))' + cast(1 as VARCHAR(20))
    --SET @c = 'select ' + cast(@i1 as varchar(20))+'1'
    --print @c
    exec (@c)
    --select @a=@i1

    --print @c
    select @a=@i1

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #761256
    Hi Sivs,

    Your query is really confusing.

    You have declared 4 variables i.e.
    @i1 INT
    ,@a INT
    ,@b VARCHAR(10)
    ,@c VARCHAR(100)
    then in the statement --SET @b = '@i' + '1' ,
    you are using is varaible '@i' which is not declared.

    So obvoiusly it will throw error.

  • #761259
    Hi
    Dipti

    your query this
    SET @c = 'select @a=@i' + '1'

    But Question look this

    SET @c = 'select @a=@i' + '1'

    here Query concatenate this

    select @a=@i1

    so i1 not i

    i1 already declared in top look this

    DECLARE @i1 INT

    Name : Dotnet Developer-2015
    Email Id :kumaraspcode2009@gmail.com

    'Not by might nor by power, but by my Spirit,' says the LORD Almighty.

  • #763516
    Hello,

    Try this :-

    DECLARE @i1 INT
    DECLARE @a INT
    DECLARE @b VARCHAR(10)
    DECLARE @c VARCHAR(100)

    SET @i1 = 1
    SET @b = convert(varchar(5),@i1)
    SET @a = @i1
    SET @c = 'select ' + convert(varchar(50), @a)
    exec (@c)


Sign In to post your comments