简体   繁体   中英

Retrieve column value using column name in SQL Server

I am using SSMS 2014, I want to retrieve column value using column name in SQL Server. The user can select any column from the table and retrieve the value of that column.

Example:

exec employee Name 'karl' 

Output as follows:

| Id | Name | ManagerId | ManagerName | Gender | Dept |
| 5  | Karl |   1       | Luke        |   M    |  1   |

I am creating procedure to resolve this but i am not getting any value in output.

Create proc sp_getEmpDetail
    @colname varchar(50),
    @colvalue varchar(50)
as
    Select * 
    from employees1 
    where @colname = @colvalue

I am not getting any value in output.

When I am debugging it then variables are getting value which I supplied.

Please help to resolve this.

Thanks in advance.

--for this you need to create a dynamic Query

Create proc sp_getEmpDetail
@colname varchar(50),
@colvalue varchar(50)
AS
    DECLARE @Sql_String NVARCHAR(MAX)

    SET @Sql_String='Select * from employees1  where '+@colname+' = '''+@colvalue+''''
    PRINT @Sql_String
    EXEC(@Sql_String)
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