Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use special characters in column name in SQL Server and C# data table

I have a doubt can I use special characters %, $, +, -, # in SQL Server table column name and C# data table?

I tried to create a table with these characters in SQL Server the table is created, but I want to know its possible or not?

like image 764
mohanasundaram p Avatar asked Jan 01 '23 22:01

mohanasundaram p


2 Answers

As explained you can since your column name is between square brackets, but it is not a good practice use spaces and special characters in column names.

CREATE TABLE [TABLE1] (ID UNIQUEIDENTIFIER, [% Column1] INT, [$ Column2] INT, [+ Column3] 
INT, [- Column4] INT, [# Column5] INT);

INSERT INTO [TABLE1] (ID, [% Column1], [$ Column2], [+ Column3], [- Column4], [# Column5])
VALUES ('8C012194-5D8A-4A58-B225-F33F60875499',1, 2, 3, 4, 5)

If you are using Entity Framework you can map your column to your model class like this:

[Table("Table1")]
public class Test 
{
  public Guid Id { get; set; }

  [Column("% Column1")]
  public int Column1 { get; set; }

  [Column("$ Column2")]
  public int Column2 { get; set; }

  [Column("+ Column3")]
  public int Column3 { get; set; }

  [Column("- Column4")]
  public int Column4 { get; set; }

  [Column("# Column5")]
  public int Column5 { get; set; }

}
like image 142
Flavio Francisco Avatar answered Jan 13 '23 11:01

Flavio Francisco


Azure sql supports these special characters in your column name.

Because the SQL Server datatype column_name is nvarchar( 128 ). enter image description here

You can get this form this document: COLUMNS (Transact-SQL)

For C# , as mukesh kudi said, you should use [] brackets.

For example, if you want to select the column with special character '#', the code should like this:

var rows = dt.Select("","[#]");

You can reference this blog: How to access an column with special characters using DataTable.Select()?

Hope this helps.

like image 33
Leon Yue Avatar answered Jan 13 '23 11:01

Leon Yue