Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring variable type based on a column type

Tags:

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?

like image 386
Bernard Dy Avatar asked Apr 21 '10 14:04

Bernard Dy


People also ask

Is used to define a variable of the TYPE of a column of a table?

The %TYPE attribute provides the datatype of a variable or table column. This is particularly useful when declaring variables that will hold values of a table column.

Which of the following is used to ensure the TYPE compatibility between variable declared and columns of a table?

The %TYPE attribute, used in PL/SQL variable and parameter declarations, is supported by the data server. Use of this attribute ensures that type compatibility between table columns and PL/SQL variables is maintained.

Which keyword is used to assign data type of an existing table column or variable to another variable?

Declaring variables as the type table_name %ROWTYPE is a convenient way to transfer data between database tables and PL/SQL.

What is %type and Rowtype?

%ROWTYPE. Specifies that the record field data types are to be derived from the column data types that are associated with the identified table or view. Record fields do not inherit any other column attributes, such as, for example, the nullability attribute.


2 Answers

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.

like image 51
D'Arcy Rittich Avatar answered Sep 21 '22 05:09

D'Arcy Rittich


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.

like image 23
Jeremy Avatar answered Sep 25 '22 05:09

Jeremy