0

How can I use the table name as a parameter in a stored procedure?

I am doing it like this but I'm getting an error

ALTER PROCEDURE [dbo].[usp_TablesReporting_GetTableData]
    @tableName as VARCHAR(100)
AS
BEGIN
    SELECT * FROM @tablename
END

Error:

Must declare the table variable "@tableName"

3 Answers 3

2

Try this

DECLARE @cmd AS NVARCHAR(max)
SET @cmd = N'SELECT * FROM ' + @table_name
EXEC sp_executesql @cmd
Sign up to request clarification or add additional context in comments.

Comments

1

This is not possible in that format. You need to embed the variable into dynamic SQL and execute it.

DECLARE @TABLENAME NVARCHAR(100), @SQL NVARCHAR(4000)
SET @TABLENAME = 'myTable'
SET @SQL = 'SELECT * FROM ' + @TABLENAME
EXEC SP_EXECUTESQL @SQL

Comments

1

You can do something like below:

ALTER PROCEDURE [dbo].[usp_TablesReporting_GetTableData]

    @tableName AS VARCHAR(100)= NULL -- NULL default value
AS
DECLARE @query AS NVARCHAR(max)= 'SELECT * FROM ' + @tablename

-- Validate the @tablename parameter.
IF @tablename IS NULL
BEGIN
   PRINT 'ERROR: You must specify the table name.'
   RETURN
END

exec sp_executesql @query

RETURN
GO

Here, i have just created and executed dynamic query.

To achieve in other manner using SqlCMD mode you can take reference from here.

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.