Search code examples
sqlsql-serversql-server-2005t-sqltemp-tables

SQL Server, Problem creating temp table in TSQL


Hi when i execute the following TSQL, i get the error message below. But there is nothing wrong with the SQL syntax is there?

create table #tb ([t1] tinyint, [t2] varchar(50))
insert into #tb values
    (1, 'a'), 
    (2, 'b')

Msg 102, Level 15, State 1, Line 3 Incorrect syntax near ','.

There is nothing else in the SQL query window. Running SQL Server 2005.


Solution

  • As jmoreno mentions, theVALUES (), () syntax is SQL Server 2008+ supported but you tagged this as SQL Server 2005.

    Use:

    CREATE TABLE #tb ([t1] tinyint, [t2] varchar(50))
    
    INSERT INTO #tb 
    SELECT 1, 'a'
    UNION ALL
    SELECT 2, 'b'
    

    It's also possible to do this in a single query, using the SELECT ... INTO clause, but the temp table can't already exist:

    SELECT *
      INTO #tb
      FROM (SELECT CAST(1 AS TINYINT) AS t1, 
                   CAST('a' AS VARCHAR(50)) AS t2
            UNION ALL
            SELECT 2, 'b') x