sp_addtype (Transact-SQL) Creates an alias data type. Important |
|---|
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. Use CREATE TYPE instead. |
Transact-SQL Syntax Conventions

Syntax
sp_addtype [ @typename = ] type,
[ @phystype = ] system_data_type
[ , [ @nulltype = ] 'null_type' ] ;

Arguments
- [ @typename= ] type
Is the name of the alias data type. Alias data type names must follow the rules for identifiers and must be unique in each database. type is sysname, with no default. - [ @phystype=] system_data_type
Is the physical, or SQL Server supplied, data type on which the alias data type is based.system_data_type is sysname, with no default, and can be one of these values: bigint | binary(n) | bit | char(n) | datetime | decimal | float | image | int | money | nchar(n) | ntext | numeric | nvarchar(n) | real | smalldatetime | smallint | smallmoney | sql_variant | text | tinyint | uniqueidentifier | varbinary(n) | varchar(n) |
Quotation marks are required around all parameters that have embedded blank spaces or punctuation marks. For more information about available data types, see Data Types (Transact-SQL). - n
Is a nonnegative integer that indicates the length for the chosen data type. - P
Is a nonnegative integer that indicates the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. For more information, see decimal and numeric (Transact-SQL). - s
Is a nonnegative integer that indicates the maximum number of decimal digits that can be stored to the right of the decimal point, and it must be less than or equal to the precision. For more information, see decimal and numeric (Transact-SQL). - [ @nulltype = ] 'null_type'
Indicates the way the alias data type handles null values. null_type is varchar(8), with a default of NULL, and must be enclosed in single quotation marks ('NULL', 'NOT NULL', or 'NONULL'). If null_type is not explicitly defined by sp_addtype, it is set to the current default nullability. Use the GETANSINULL system function to determine the current default nullability. This can be adjusted by using the SET statement or ALTER DATABASE. Nullability should be explicitly defined. If @phystype is bit, and @nulltype is not specified, the default is NOT NULL. Note |
|---|
The null_type parameter only defines the default nullability for this data type. If nullability is explicitly defined when the alias data type is used during table creation, it takes precedence over the defined nullability. For more information, see ALTER TABLE (Transact-SQL) and CREATE TABLE (Transact-SQL). |

Return Code Values
0 (success) or 1 (failure)

Result Sets

Remarks
An alias data type name must be unique in the database, but alias data types with different names can have the same definition. Executing sp_addtype creates an alias data type that appears in the sys.types catalog view for a specific database. If the alias data type must be available in all new user-defined databases, add it to model. After an alias data type is created, you can use it in CREATE TABLE or ALTER TABLE, and also bind defaults and rules to the alias data type. All scalar alias data types that are created by using sp_addtype are contained in the dbo schema. Alias data types inherit the default collation of the database. The collations of columns and variables of alias types are defined in the Transact-SQL CREATE TABLE, ALTER TABLE and DECLARE @local_variable statements. Changing the default collation of the database applies only to new columns and variables of the type; it does not change the collation of existing ones. Security Note |
|---|
For backward compatibility purposes, the public database role is automatically granted REFERENCES permission on alias data types that are created by using sp_addtype. Note when alias data types are created by using the CREATE TYPE statement instead of sp_addtype, no such automatic grant occurs. |
Alias data types cannot be defined by using the SQL Server timestamp, table, xml, varchar(max), nvarchar(max) or varbinary(max) data types.

Permissions
Requires membership in the db_owner or db_ddladmin fixed database role.

Examples
A.Creating an alias data type that does not allow for null valuesThe following example creates an alias data type named ssn (social security number) that is based on the SQL Server-supplied varchar data type. The ssn data type is used for columns holding 11-digit social security numbers (999-99-9999). The column cannot be NULL. Notice that varchar(11) is enclosed in single quotation marks because it contains punctuation (parentheses).
USE master;
GO
EXEC sp_addtype ssn, 'varchar(11)', 'NOT NULL';
GO
B.Creating an alias data type that allows for null valuesThe following example creates an alias data type (based on datetime) named birthday that allows for null values.
USE master;
GO
EXEC sp_addtype birthday, datetime, 'NULL';
C.Creating additional alias data typesThe following example creates two additional alias data types, telephone and fax, for both domestic and international telephone and fax numbers.
USE master;
GO
EXEC sp_addtype telephone, 'varchar(24)', 'NOT NULL';
GO
EXEC sp_addtype fax, 'varchar(24)', 'NULL';
GO

See Also
|
sp_addtype (Transact-SQL) Crea un tipo de datos de alias. Importante |
|---|
Esta característica se quitará en una versión futura de Microsoft SQL Server. Evite utilizar esta característica en nuevos trabajos de desarrollo y tenga previsto modificar las aplicaciones que actualmente la utilizan. En su lugar, utilice CREATE TYPE. |
Convenciones de sintaxis de Transact-SQL

Sintaxis
sp_addtype [ @typename = ] type,
[ @phystype = ] system_data_type
[ , [ @nulltype = ] 'null_type' ] ;

Argumentos
- [ @typename= ] type
Es el nombre del tipo de datos de alias. Los nombres de los tipos de datos de alias tienen que seguir las reglas de los identificadores y deben ser exclusivos en cada base de datos. type es de tipo sysname y no tiene ningún valor predeterminado. - [ @phystype=] system_data_type
Es el tipo de datos físico, o proporcionado por SQL Server, en el que se basa el tipo de datos de alias. system_data_type es de tipo sysname, no tiene valor predeterminado y puede tener uno de estos valores: bigint | binary(n) | bit | char(n) | datetime | decimal | float | image | int | money | nchar(n) | ntext | numeric | nvarchar(n) | real | smalldatetime | smallint | smallmoney | sql_variant | text | tinyint | uniqueidentifier | varbinary(n) | varchar(n) |
Se requieren comillas para delimitar los parámetros que tengan espacios o signos de puntuación incrustados. Para obtener más información acerca de los tipos de datos disponibles, vea Tipos de datos (Transact-SQL). - n
Es un entero no negativo que indica la longitud del tipo de datos elegido. - P
Es un entero no negativo que indica el número total máximo de cifras decimales que se pueden almacenar, a ambos lados del separador decimal. Para obtener más información, vea decimal y numeric (Transact-SQL). - s
Es un entero no negativo que indica el número máximo de cifras decimales que se pueden almacenar a la derecha del separador decimal, y tiene que ser menor que la precisión decimal o igual a ésta. Para obtener más información, vea decimal y numeric (Transact-SQL). - [ @nulltype = ] 'null_type'
Indica la forma en que el tipo de datos de alias trata los valores nulos. null_type es de tipo varchar(8), su valor predeterminado es NULL y tiene que estar entre comillas simples ('NULL', 'NOT NULL' o 'NONULL'). Si no se define explícitamente null_type en sp_addtype, se establece según la nulabilidad predeterminada actual. Utilice la función de sistema GETANSINULL para determinar la nulabilidad predeterminada actual. Esto se puede ajustar mediante la instrucción SET o ALTER DATABASE. La nulabilidad se tiene que definir explícitamente. Si @phystype es de tipo bit y @nulltype no se especifica, el valor predeterminado es NOT NULL. Nota |
|---|
El parámetro null_type solo define la nulabilidad predeterminada de este tipo de datos. Si la nulabilidad se define explícitamente cuando se utiliza este tipo de datos de alias durante la creación de una tabla, ésta tendrá prioridad sobre la nulabilidad definida. Para obtener más información, vea ALTER TABLE (Transact-SQL) y CREATE TABLE (Transact-SQL). |

Valores de código de retorno

Conjuntos de resultados

Comentarios
Los nombres de los tipos de datos de alias tienen que ser exclusivos en la base de datos, pero tipos de datos de alias con distintos nombres pueden tener la misma definición. La ejecución de sp_addtype crea un tipo de datos de alias que aparece en la vista de catálogo sys.types para una base de datos específica. Si el tipo de datos de alias tiene que estar disponible en todas las nuevas bases de datos definidas por el usuario, agréguelo a model. Después de crear un tipo de datos de alias, puede utilizarse en CREATE TABLE o ALTER TABLE, así como enlazarse a valores predeterminados y reglas. Todos los tipos de datos de alias escalares que se crean mediante sp_addtype están contenidos en el esquema dbo. Los tipos de datos de alias heredan la intercalación predeterminada de la base de datos. La intercalación de columnas y variables de tipos de alias se definen en las instrucciones Transact-SQL CREATE TABLE, ALTER TABLE y DECLARE @local_variable. Cualquier cambio en la intercalación predeterminada de la base de datos solo se aplica a las columnas y variables nuevas del tipo; no afecta la intercalación de los tipos existentes. Nota de seguridad |
|---|
Por compatibilidad con versiones anteriores, al rol de base de datos public se le concede automáticamente el permiso REFERENCES sobre los tipos de datos de alias que se crean mediante sp_addtype. Tenga en cuenta que cuando los tipos de datos de alias se crean con la instrucción CREATE TYPE en lugar de sp_addtype, ese permiso no se concede automáticamente. |
Los tipos de datos de alias no se pueden definir con los tipos de datos timestamp, table, xml, varchar(max), nvarchar(max) o varbinary(max) de SQL Server.

Permisos
Es necesario pertenecer a los roles fijos de base de datos db_owner o db_ddladmin.

Ejemplos
A.Crear un tipo de datos de alias que no permite valores NULLEn el ejemplo siguiente se crea un tipo de datos de alias denominado ssn (número de la seguridad social) que se basa en el tipo de datos varchar proporcionado por SQL Server. El tipo de datos ssn se utiliza en columnas que almacenan números de la seguridad social de 11 cifras (999-99-9999). La columna no puede ser NULL. Observe que varchar(11) está entre comillas simples porque contiene signos de puntuación (paréntesis).
USE master;
GO
EXEC sp_addtype ssn, 'varchar(11)', 'NOT NULL';
GO
B.Crear un tipo de datos de alias que permite valores NULLEn este ejemplo se crea un tipo de datos de alias (basado en el tipo de datos datetime) denominado birthday que permite valores NULL.
USE master;
GO
EXEC sp_addtype birthday, datetime, 'NULL';
C.Crear tipos de datos de alias adicionalesEn este ejemplo se crean dos tipos de datos de alias adicionales, telephone y fax, para números de teléfono y fax locales e internacionales.
USE master;
GO
EXEC sp_addtype telephone, 'varchar(24)', 'NOT NULL';
GO
EXEC sp_addtype fax, 'varchar(24)', 'NULL';
GO

Vea también
|