简体   繁体   中英

How to pass column name as well as Table Name to a stored procedure as a parameter in SQL Server?

I have a stored procedure which takes the column name as well as the table name as a parameter.

ALTER PROCEDURE [dbo].[usp_TableReporting_GetColumnNamesAndValues]
    @concatstring AS VARCHAR(100),
    @Tablename as VARCHAR(100)
AS
BEGIN
    SELECT @concatstring FROM @Tablename
END

This procedure gives me an error :

Must declare the scalar variable @TableName

although I have already declared it on the top.

use dynamic SQL:

ALTER PROCEDURE [dbo].[usp_TableReporting_GetColumnNamesAndValues]
@concatstring AS VARCHAR(100),
@Tablename as VARCHAR(100)

AS
BEGIN
    Declare @mystring varchar(max) = N'select ' +  @concatstring + ' from ' + @Tablename
    exec (@mystring)

END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM