1

I want to use tablename variable in select statement, but it is giving error

- Must declare the table variable "@table"

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
   declare @table varchar(50)
   declare @add varchar(150)
   set @table = 'DBTest..testMaster'
   select @add = address from @table where id=@id and name=@name
END

This is a snap shot of my code

3
  • are you trying to create a table variable? Commented Aug 12, 2014 at 13:12
  • You can't use a variable for a table name like this, it's only possible in Dynamic SQL because the variable can not be used in place of object names or keywords Commented Aug 12, 2014 at 13:15
  • Possible duplicate of Table name as variable Commented Jan 8, 2020 at 8:57

3 Answers 3

3

You need to use dynamic sql for this:

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
   declare @table varchar(50)
   declare @add varchar(150)
   set @table = 'DBTest..testMaster'
   DECLARE @sql NVARCHAR(MAX)
   SELECT @sql = 'select @add = address from ' + @table + ' where id= ' + @id + ' and name= ' + @name
   EXEC sp_executesql @sql

END
Sign up to request clarification or add additional context in comments.

Comments

2

You can't use a variable for your table name. When you do select address from @table SQL expects @table to be a variable of the table type, not a scalar.

You're looking to do something like this:

ALTER PROCEDURE testTblName
(
    @id INT,
    @name VARCHAR(50)
)
AS
BEGIN
    DECLARE @table VARCHAR(50),
            @add VARCHAR(150),
            @params VARCHAR(200),
            @sql VARCHAR(200);

    SET @params = '@add VARCHAR(50) OUTPUT';

    SET @table = 'DBTest..testMaster'

    SET @sql = 'SELECT @add = address FROM ' + @table + ' WHERE id=' + @id + ' AND name=' + @name

    EXEC sp_executesql @sql, @params, @add OUTPUT;

    ...
    ...
END

Comments

0

I think, u will have to give something like this.

alter PROCEDURE testTblName
(
@id int,
@name varchar(50)
)
AS
BEGIN
    declare @table varchar(50)
    declare @add varchar(Max)
    set @table = 'DBTest..testMaster'

    Set  @add = 'Select address from ' + @table + ' where id = ' + CAST(@id AS VARCHAR(10)) + ' and name = ' + @name

    Exec(@add)
END

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.