Repository: tobymao/sqlglot

Issue:
bug(mssql): incorrect syntax for creating quoted temporary table
```python
[ins] In [1]: import sqlglot as sg

[ins] In [2]: sg.__version__
Out[2]: '23.12.3.dev11'

[ins] In [3]: exp = sg.parse_one(
         ...:     "CREATE TEMPORARY TABLE 'temptest' (name VARCHAR);", dialect="duckdb"
         ...: )

[ins] In [4]: exp
Out[4]: 
Create(
  this=Schema(
    this=Table(
      this=Identifier(this=temptest, quoted=True)),
    expressions=[
      ColumnDef(
        this=Identifier(this=name, quoted=False),
        kind=DataType(this=Type.VARCHAR, nested=False))]),
  kind=TABLE,
  properties=Properties(
    expressions=[
      TemporaryProperty()]))

[ins] In [5]: exp.sql(dialect="tsql")
Out[5]: 'CREATE TABLE #[temptest] (name VARCHAR)'
```

`#[temptest]` is invalid syntax.  I am not sure of how to use the `#` temp indicator with a quoted identifier -- it IS possible to create a temporary table that requires quoting but the only way I have figured out how to do it is by specifying the catalog and database explicitly, e.g. 

```sql
CREATE TABLE tempdb.dbo.[quoted@identifer] ([name] VARCHAR(max))
```

**Official Documentation**
https://learn.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver16#syntax-options
https://learn.microsoft.com/en-us/sql/relational-databases/databases/database-identifiers?view=sql-server-ver16#classes-of-identifiers

xref: https://github.com/ibis-project/ibis/issues/9095


Discussion:

Patch:
diff --git a/sqlglot/dialects/tsql.py b/sqlglot/dialects/tsql.py
index 54fc4318..2e8ddf21 100644
--- a/sqlglot/dialects/tsql.py
+++ b/sqlglot/dialects/tsql.py
@@ -913,7 +913,7 @@ class TSQL(Dialect):
                 isinstance(prop, exp.TemporaryProperty)
                 for prop in (properties.expressions if properties else [])
             ):
-                sql = f"#{sql}"
+                sql = f"[#{sql[1:]}" if sql.startswith("[") else f"#{sql}"
 
             return sql
 


Test patch:
diff --git a/tests/dialects/test_tsql.py b/tests/dialects/test_tsql.py
index 5550a404..1538d47a 100644
--- a/tests/dialects/test_tsql.py
+++ b/tests/dialects/test_tsql.py
@@ -780,6 +780,14 @@ class TestTSQL(Validator):
             "CREATE PROCEDURE foo AS BEGIN DELETE FROM bla WHERE foo < CURRENT_TIMESTAMP - 7 END",
             "CREATE PROCEDURE foo AS BEGIN DELETE FROM bla WHERE foo < GETDATE() - 7 END",
         )
+
+        self.validate_all(
+            "CREATE TABLE [#temptest] (name VARCHAR)",
+            read={
+                "duckdb": "CREATE TEMPORARY TABLE 'temptest' (name VARCHAR)",
+                "tsql": "CREATE TABLE [#temptest] (name VARCHAR)",
+            },
+        )
         self.validate_all(
             "CREATE TABLE tbl (id INTEGER IDENTITY PRIMARY KEY)",
             read={