开发者

insert into sql table column as GUID

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(stAddC开发者_运维知识库olumn, 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?


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.


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜