raghu rajvanshi
raghu rajvanshi

Reputation: 17

How to write a procedure in sql server that takes table name as a input parameter and displays the data in the table as an output

How to write a procedure in sql server that takes table name as a input parameter and displays the data in the table as an output

create procedure Fetch_Table_Data


    @Table_name varchar(50)
    'Select* from'+'@Table_name'

This is showing error

Upvotes: 0

Views: 57

Answers (1)

fly_ua
fly_ua

Reputation: 1054

use sp_executesql

"Executes a Transact-SQL statement or batch that can be reused many times, or one that has been built dynamically. "

In your case it wil be

EXECUTE sp_executesql 'Select * from'+@Table_name

UPD: Complete example

declare @tname nvarchar(50), @sql nvarchar(50)
select @tname = 'dbo.SomeTable'
select @sql = 'Select * from ' + @tname
EXECUTE sp_executesql @sql

Upvotes: 1

Related Questions