support@codebucket.net

How to pass column name as parameters in a stored procedure

How to pass column name as parameters in a stored procedure

K. M. Shawkat Zamil | October 19, 2022

Hello Developers,

In this demonstration, I will show how you pass a column name in MSSQL Server stored procedure as a parameter.

Suppose I have a table that has three column names Level1, Level2, and Level3. If I have to pass a column name for creating a conditional statement, then it creates a hassle. For that, you can follow the below code:

 

CREATE procedure [dbo].[stored_procedure_name]
	@UserLevel as varchar(10)
AS

DECLARE @SQL VARCHAR(8000)

SET @SQL = 'SELECT * FROM TABLENAME WHERE (' +  @UserLevel + ' = '''' )'

PRINT @SQL

EXEC (@SQL)

 

The print() the statement will print the query for your modification. Finally, the exec() function will execute the written SQL.

 

Hope this might help in the development journey.

 

Read More: How to get the first date and last date of the month from GETDATE() in mssql

K. M. Shawkat Zamil

K. M. Shawkat Zamil

Senior Software Engineer

I am a Senior Software Engineer in a reputed company in Bangladesh. I am a big fan of Laravel, PHP Programming, MSSQL Server, MySql, JavaScript, and lots more. I love to help people who are especially eager to learn. I believe in patience and motivation.