Get column value from sql row column name
Is it possible to get multiple column values ββwhen we have a column name as a string For example, if I have a table Test
and I have columns FirstName , LastName , Address
.
Now when I want to get the value of all three columns, but I want to make this dynamic to just pass the column name of the row, I get the values ββfor those columns
Example
Select
(select column_name from metadata )
from source table
+3
source to share
3 answers
You can build your query dynamically in code. However, it must be reliable so that it is not susceptible to SQL injection. Something like that:
string commandString = "select {0} from SomeTable";
SqlCommand command = new SqlCommand();
command.CommandText = string.Format(commandString, "selected column names");
command.EndExecuteReader();
In SQL:
declare @query nvarchar(500)
set @query = replace('select 0 from author','0','column names from some parameter')
execute sp_executesql @query
Update 2: Does this do what you need?
declare @query nvarchar(500)
DECLARE @columnNames varchar(1000)
set @columnNames = ''
SELECT @columnNames = @columnNames + column_name + ',' FROM metadata
set @query = replace('select 0 from source_table','0',SUBSTRING(@columnNames,0,LEN(@columnNames)-1))
execute sp_executesql @query
+1
source to share
You have to use dynamic SQL:
http://www.sqlusa.com/bestpractices/dynamicsql/
Dynamic PIVOT also takes into account:
0
source to share