简体   繁体   中英

How to create SQL procedure to select dynamic column from dynamic table where dynamic table

I need to create procedure to select dynamic column from dynamic data where dynamic value

Craete procedure SelectColumn
@tableName NVARCHAR(MAX),
@id int,
@ColumnName NVARCHAR(MAX)

as
begin
DECLARE @SQLString1 NVARCHAR(MAX)
SET @SQLString1= 'Select '+ @ColumnName + ' From ' + @TableName +' where id= '+@id
    print @SQLString1
    EXEC (@SQLString1)
end

When execute show this error

Conversion failed when converting the nvarchar value 'Select Email From Member where id= ' to data type int.

when delete where id= '+@id and set 'where id=1' the procedure success, but I need use where id=@id .

试试这个CAST(@id AS VARCHAR)

SET @SQLString1= 'Select '+ @ColumnName + ' From ' + @TableName +' where id= '+CAST(@id AS VARCHAR)

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