Search code examples
sql-serversql-server-2008collationtemp-tables

SQL SERVER: Define same database collation for temporary table


I have a script in SQL Server. In that script I create a temporary table like this:

CREATE TABLE #tmpTbl(ID char(36) NOT NULL, Field1 char(36) NOT NULL, Field2 varchar(50) NOT NULL, Field3 varchar(50))

to set the collation for entire temporary table I do:

CREATE TABLE #tmpTbl(ID char(36) collate Modern_Spanish_CI_AS NOT NULL , Field1 char(36) collate Modern_Spanish_CI_AS NOT NULL , Field2 varchar(50) collate Modern_Spanish_CI_AS NOT NULL , Field3 varchar(50) collate Modern_Spanish_CI_AS)

As you see, I apply collation for each column. So I am trying to do below:

  1. Instead of applying collation to each column of the temporary table, is there any possibility to apply collation to all columns of temporary table at onces?
  2. Instead of indicating manually the collation Modern_Spanish_CI_AS that the database where script is executed has, is there any way to get the collation from the database through a variable and then set it to temporary columns?

for example in this last case:

DECLARE @Collation = getdatabasecollation  --> Get current database collation where script is executed.

and then:

CREATE TABLE #tmpTbl(ID char(36) collate @Collation NOT NULL , Field1 char(36) collate @Collation NOT NULL, Field2 varchar(50) collate @Collation NOT NULL , Field3 varchar(50) collate @Collation)

or has I have told in point 1, set this collation to entire temporary table.


Solution

  • Just use COLLATE DATABASE_DEFAULT

    CREATE TABLE #tmpTbl
      (
         ID     CHAR(36) COLLATE DATABASE_DEFAULT NOT NULL,
         Field1 CHAR(36) COLLATE DATABASE_DEFAULT NOT NULL,
         Field2 VARCHAR(50) COLLATE DATABASE_DEFAULT NOT NULL,
         Field3 VARCHAR(50) COLLATE DATABASE_DEFAULT NULL
      )