How To Write An Attribute Name To The Select Query Dynamically
I have a table including: ID Name Period0Id Period1Id Period2Id What I would like to receive data based on a user-defined parameter @check. Lets assume: declare @check int = 1; I
Solution 1:
Your table looks like it is not in first normal form.
Instead of three columns for Period0Id to Period2Id you could have a column for PeriodIndex with values of (0,1,2) and a single column for PeriodId and then it would be just a WHERE PeriodIndex = @Check
You can't select a column using string interpolation with a variable as you are attempting. You can use dynamic SQL to create the SQL String dynamically. Or simply hardcode the options if they all have the same dataype.
Select ID,
Name,
StatusId =CASE@CheckWHEN0THEN Period0Id
WHEN1THEN Period1Id
WHEN2THEN Period2Id
ENDFrom mytable
Solution 2:
Here is an alternative way that will create dynamic columns, which is essentially using your original query:
DECLARE@checkVARCHAR=1DECLARE@sqlquery NVARCHAR(MAX)
SET@sqlquery= N'SELECT ID, Name, StatusId = Period'+@check+'Id
FROM mytable'EXEC sp_executesql @sqlquery
Post a Comment for "How To Write An Attribute Name To The Select Query Dynamically"