tags:

views:

81

answers:

3

I have tried with ado.net create table columnName with unique name. as uniquename I use new Guid()

    Guid sysColumnName = new Guid();
    sysColumnName = Guid.NewGuid();

    string stAddColumn = "ALTER TABLE " + tableName + " ADD " + sysColumnName.ToString() + " " + convertedColumnType + "  NULL";
    SqlCommand cmdAddColumn = new SqlCommand(stAddColumn, con);
    cmdAddColumn.ExecuteNonQuery();
    con.Close();

and it fails:

System.Data.SqlClient.SqlException: Incorrect syntax near '-'. в System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) в System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)

now question, how can i fix it, or how can use different way to create unique column?

+6  A: 

You need to use [...] to escape the column name that contains minus signs, or better still: don't create columns (or tables) with random names.

Mark Byers
A: 

try replacing the dashes with underscores

var sysColumnName = Guid.NewGuid.ToString().Replace('-', '_');

Also, you shouldn't be creating sql in this way. You should be using parameterized commands.

Michael Meadows
A: 

This will format guid without "-" signs:

string columnName = Guid.ToString("N")

But it is bad practice to create columns with random names, are you sure you a going the right way?

Andrew Bezzub