Ramandeep Singh
Ramandeep Singh

Reputation: 83

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.

Upvotes: 2

Views: 660

Answers (1)

Alfaiz Ahmed
Alfaiz Ahmed

Reputation: 1726

--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

Upvotes: 4

Related Questions