How to make a query with dynamic column in sql server 2012 -


i have sample code below. result such takes these columns varchar type.

declare @col1 varchar(80)='[column1]' declare @col2 varchar(80)='[column2]' select @col1,@col2 mytable 

you have use dynamic sql:

declare @col1 varchar(80) = 'column1'; declare @col2 varchar(80) = 'column2';  declare @sql nvarchar(max);  select @sql = 'select ' + quotename(@col1) + ', ' + quotename(@col2) + ' mytable;';  exec sp_executesql @sql; 

note have make sure column names real column names. need parameterize query added security. if of these wrong, may create huge security problems.


Comments

Popular posts from this blog

Load Balancing in Bluemix using custom domain and DNS SRV records -

oracle - pls-00402 alias required in select list of cursor to avoid duplicate column names -

python - Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] error -