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?

Upvotes: 7

Views: 33340

Answers (3)

Flavio Francisco
Flavio Francisco

Reputation: 775

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; }

}

Upvotes: 9

Leon Yue
Leon Yue

Reputation: 16411

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.

Upvotes: 2

mukesh kudi
mukesh kudi

Reputation: 729

Welcome to SO,You can have column name with special character or space but you have to use

square bracket []

in order to access those columns.

eg.

Table
%ID
1
2
3


Select [%ID] from Table

For more information on column and table name rules for MSSQL Server you can check out msdn

Upvotes: 1

Related Questions