Adding column-name dynamically in alter table

こ雲淡風輕ζ 提交于 2019-12-10 12:30:13

问题


I am developing a web application and need to use ALTER Table in it. Here is my code:

ALTER TABLE [tablename] ADD [column-name] [Type] DEFAULT [default-value] NULL/NOT NULL 

Now i want to change [column-name] dynamically by a text box. How can i do that? In addition i used @name in AddWithValue, but it doesn't work! Can any body help me? Thanks

here is my whole code:

SqlConnection sqlconn4 = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString);
                   SqlCommand sqlcomm4 = new SqlCommand("ALTER TABLE aspnet_Membership ADD @column int DEFAULT 0 NOT NULL", sqlconn4);

                    sqlcomm4.Parameters.AddWithValue("@column", TextBox1.Text);
                    sqlconn4.Open();
                    sqlcomm4.ExecuteNonQuery();
                    sqlconn4.Close();

回答1:


with sp_rename procedure you can change column name.

sp_RENAME 'Table_First.Name', 'NameChange' , 'COLUMN'

http://blog.sqlauthority.com/2008/08/26/sql-server-how-to-rename-a-column-name-or-table-name/

public void AddNewColumn(string tableName, string columName, string dataType)
    {
        string commandText = String.Format("ALTER TABLE {0} ADD {1} {2} ", tableName,columName,dataType);

        using (var sqlConnection = new SqlConnection("===="))
        {
            var cmd = sqlConnection.CreateCommand();
            cmd.CommandText = commandText;

            sqlConnection.Open();
            cmd.ExecuteNonQuery();
        }
    }



回答2:


It's possible only with dynamic SQL queries:

Declare @SQL VarChar(1000)

SELECT @SQL = 'ALTER TABLE my_table ADD ' + @column + ' INT'

Exec (@SQL)



回答3:


try the below thing..

dataTable.Columns["column-name"].ColumnName = "updated column-name";




回答4:


Hmmm, perhaps posting a sample of your code would help. For example, is your column-name variable a static variable? If the variable is not declared static it will be declared with its default value every time the Alter table method is called and the changes made to it by the textbox textChanged event.

On the other hand if your current problem is trying to get the dynamic portion to work are you using the textChanged event of your textbox to alter the column-name variable?

Once again more information would be greatly appreciated.



来源:https://stackoverflow.com/questions/14808826/adding-column-name-dynamically-in-alter-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!