简体   繁体   中英

How to insert dynamic column name in C# SQL query?

I tried to insert a dynamic column name into my c# query string as follows.

"select @columnname from table"

command.Parameters.AddWithValue("@columnname", obj.ColumnName);

but I could not get the desired result. Can somebody help me?

You cannot parametrize column names directly; however, you can select a column with a CASE statement

SELECT CASE @columnname WHEN 'aaa' THEN aaa
                        WHEN 'bbb' THEN bbb
                        WHEN 'ccc' THEN ccc
       END AS TheColumn
FROM table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM