Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

Hello all I'm having 1 Question with following query syntax

 ALTER TABLE table_name
 ADD column_name column-definition;

Question is can we use parameters to column_name field like @column_name? Because I'm creating columns which Column name is supplied by front end as a parameter. for example

ALTER TABLE table_name
ADD @column_name varchar(250);

this is giving error so any alternate for this?

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

Perhaps try:

DECLARE @sql varchar(max);
SET @sql = 'ALTER TABLE table_name ADD ' + @column_name + ' varchar(250);';
EXEC (@sql);
share|improve this answer
2  
To be on the safe side from malicious or ignorant end-users you should use quotename(). quotename(@column_name) –  Mikael Eriksson Apr 4 '12 at 13:04
    
Another good option. –  OliverAsmus Apr 4 '12 at 14:07
    
@MikaelEriksson what are the advantages of using quotename(@column_name) over @column_name? –  M.S.Nayak Apr 5 '12 at 5:30
1  
@M.S.Nayak - It will remove (I belive) the risk of SQL-injection and it will allow your column names to contain otherwise invalid characters like space. For more info you can have a look here: The Curse and Blessings of Dynamic SQL –  Mikael Eriksson Apr 5 '12 at 5:36
    
@MikaelEriksson Thanks I got it referred blackhat.com/presentations/bh-usa-06/BH-US-06-Neerumalla.pdf –  M.S.Nayak Apr 5 '12 at 7:32
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.