You can't replace a column's name, which needs to be a literal, with a variable. You could do this with dynamic SQL, but unless you really know how to use it, I don't recommend you go down that route.
Considering the simplicity of your table, I suggest a "few" OR
clauses:
SELECT [Value]
FROM dbo.YourTable
WHERE (@@CharIndex = 0 AND [0] = @CharValue)
OR (@@CharIndex = 1 AND [1] = @CharValue)
OR (@@CharIndex = 2 AND [2] = @CharValue)
OPTION (RECOMPILE);
I really, as well, recommend better names that 0
, 1
and 2
. Don't use object names that require delimit identification.
db<>fiddle
If you "must" do this with dynamic SQL, you would need to do the following. Note, however, that using dynamic SQL comes with a lot of considerations. If you do not understand the security implications of dynamic SQL, you should not be using this. In truth, I would suggest you should be changing your design:
DECLARE @CharValue char(1) = 'c',
@CharIndex sysname = N'0';
DECLARE @SQL nvarchar(MAX);
SET @SQL = N'SELECT [Value] AS [ColumnValue] FROM dbo.YourTable WHERE ' + QUOTENAME(@CharIndex) + N' = @CharValue;';
--PRINT @SQL;
EXEC sys.sp_executesql @SQL, N'@CharValue char(1)', @CharValue;
DB<>Fiddle
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…