Declaring variable type based on a column type

20,173

Solution 1

No you can't do this. The closest equivalent is User-Defined Data Types. This will give you a layer of abstraction that may help, but it is not the same as deriving a type from a column.

Solution 2

It may skirt the real issue, but you can "cheat" a little bit by

Select *
INTO #tmp
From MyTable
Where 1 = 0

Will automatically create a temp table with all columns with correct data types.

Share:
20,173
Andras Zoltan
Author by

Andras Zoltan

Corporate slave, doing a mix of all things IT, from maintaining and enhancing legacy systems to participating in business analysis, problem resolution, and international implementations.

Updated on January 04, 2020

Comments

  • Andras Zoltan
    Andras Zoltan over 4 years

    In Oracle's PL-SQL, you can declare a variable and define its type based on a table column:

    declare var1 table.column%TYPE;
    

    Is it possible to do something similar in MS SQL Server?