Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server variable columns name?

Tags:

I am wondering why I cannot use variable column name like that:

declare @a as varchar; set @a='TEST'  select @a from x; 

Thank you

like image 867
Petr Avatar asked Apr 28 '10 06:04

Petr


People also ask

How do I show column names in SQL Server?

USE db_name; DESCRIBE table_name; it'll give you column names with the type.


2 Answers

You can't do it because SQL is compiled before it knows what the value of @a is (I'm assuming in reality you would want @a to be some parameter and not hard coded like in your example).

Instead you can do this:

declare @a as varchar;  set @a='TEST'   declare @sql nvarchar(max) set @sql = 'select [' + replace(@a, '''', '''''') + '] from x'  exec sp_executesql @sql 

But be careful, this is a security vulnerability (sql-injection attacks) so shouldn't be done if you can't trust or well clean @a.

like image 155
Daniel Renshaw Avatar answered Oct 18 '22 19:10

Daniel Renshaw


Because the column names are resolved at compile time not at run time for the SQL statement.

like image 39
David M Avatar answered Oct 18 '22 17:10

David M