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