Decimal / Convertidor binario (Mirar para convertir a punto flotante binario.) Intenta mi convertidor de punto flotante. (Buscando calcular con números binarios Prueba mi calculadora binaria.) El Convertidor Decimal / Binario Este es un conversor decimal a binario y binario a decimal. It8217s diferente de la mayoría de los convertidores decimales / binarios, como calculadora de Google o calculadora de Windows, porque: Puede convertir valores fraccionarios así como enteros. Puede convertir números muy grandes y muy pequeños 8212 hasta cientos de dígitos. Los números decimales se convierten en números binarios ldquopurerdquo, no a formatos de número de computadora como complemento two8217s o binario de punto flotante IEEE. La conversión se realiza con aritmética de precisión arbitraria. Que da al convertidor su capacidad para convertir números más grandes que los que pueden caber en tamaños estándar de palabras de computadora (como 32 o 64 bits). Cómo utilizar la entrada Conversor decimal / binario Introduzca un número positivo o negativo sin comas o espacios, no expresado como una fracción o cálculo aritmético, y no en la notación científica. Los valores fraccionarios se indican con un punto de raíz (lsquo. rsquo, not lsquo, rsquo) Cambie el número de bits que desea mostrar en el resultado binario, si es diferente al valor predeterminado (sólo se aplica cuando se convierte un valor decimal fraccionario). Haga clic en lsquoConvertrsquo para convertir. Haga clic en lsquoClearrsquo para restablecer el formulario y comenzar de cero. Si desea convertir otro número, simplemente escriba sobre el número original y haga clic en lsquoConvertrsquo 8212 no es necesario hacer clic primero en lsquoClearrsquo. Salida Además del resultado convertido, se muestra el número de dígitos tanto en el número original como en el convertido. Por ejemplo, al convertir decimal 43.125 a 101011.001 binario, el número de dígitos se muestra como lsquo2.3 a 6.3rsquo. Esto significa que la entrada decimal tiene 2 dígitos en su parte entera y 3 dígitos en su parte fraccional, y la salida binaria tiene 6 dígitos en su parte entera y 3 dígitos en su parte fraccional. Los valores decimales fraccionales que son díadicos se convierten en valores binarios fraccionarios finitos y se muestran con precisión completa. Los valores decimales fraccionados que no son díadicos se convierten en valores binarios fraccionarios infinitos (repetidos), que están truncados 8212 no redondeados 8212 al número especificado de bits. En este caso, se añade una elipsis (8230) al final del número binario, y el número de dígitos fraccionarios se anota como infinito con el símbolo lsquo8734rsquo. Exploración de propiedades de conversión decimal / binario El convertidor está configurado para que pueda explorar las propiedades de conversión decimal a binaria y binaria a decimal. Puede copiar la salida del convertidor decimal a binario a la entrada del convertidor binario a decimal y comparar los resultados (asegúrese de no copiar la parte lsquo8230rsquo del número 8212 el convertidor binario lo marcará como inválido.) Un entero decimal O el valor de la división diádica convertido a binario y luego de vuelta a decimal coincide con el valor decimal original, un valor no-diádico sólo se convierte en una aproximación de su valor decimal original. Por ejemplo, 0,1 en decimal 8212 a 20 bits 8212 es 0,00011001100110011001 en binario 0,00011001100110011001 en binario es 0,09999942779541015625 en decimal. Aumentar el número de bits de precisión hará que el número convertido más cerca de la original. Puede estudiar cómo el número de dígitos difiere entre las representaciones decimal y binaria de un número. Los números enteros binarios grandes tienen alrededor de log 2 (10), o aproximadamente 3.3, veces tantos dígitos como sus equivalentes decimales. Las fracciones decimales diádicas tienen el mismo número de dígitos que sus equivalentes binarios. Los valores decimales no-diádicos, como ya se ha indicado, tienen equivalencias binarias infinitas. Otros convertidores de valor arbitrario y de precisión Fracción de binario a decimal y hexadecimal Teoría de conversión de binario a decimal y hexadecimal Este artículo le hará entender las diferencias entre los valores binarios, decimales y hexadecimales y le dirá cómo convertir un formato de valores en los otros Valores de acuerdo con el CCNA 640-802 Cisco Certified Network Associate curso detalle 2011. Estoy empezando por la numeración binaria. Los dígitos utilizados se limitan a 1 (uno) oa 0 (cero) y cada dígito se denomina 1 bit (abreviatura de dígito binario). Normalmente contamos 4 o 8 bits juntos, estos se refieren como un nibble y un byte correspondiente. El formato de valor decimal representa la atención a la numeración binaria. El formato decimal basado en 10 números. Los números binarios se ponen en un valor speck: comienzan desde la derecha y se mueven a la izquierda con todas las mota tienen el doble valor de la mota anterior. Nibble Valores Byte Valores 8 4 2 1 128 64 32 16 8 4 2 1 Muestra los valores decimales de cada ubicación de bits en un nibble y un byte. Si se pone 1 dígito en un valor de punto, entonces el nibble o byte adquiere ese valor decimal y lo agrega a cualquier otro valor que tenga 1. Pero si se pone 0 en un valor speck no contamos ese valor. Permítanme explicar, si ponemos 1 en cada punto de nibble (1111), entonces suma 8 4 2 1, para obtener un valor máximo de 15. Otro ejemplo de los valores de nibble 1010, sus medios 8 bits y 2 bits son girados On y podemos obtener el valor decimal de 10. Un ejemplo más, binario binario valor de 0110, 4 y 2 bits se activan, por lo que se encuentra el valor decimal de 6. Otra vista, los valores de byte se suman a más de 15. Permítanme explicar esto también, si contamos cada bit como 1 en un byte (11111111), obtendremos el valor decimal de 1286432168421 255. Este es un valor máximo de un byte. Quiero explicarlo más profundamente, por lo que el valor binario 01010110, muestra que los 64 16 4 2 bits están en este valor y si vamos a añadir, vamos a encontrar este 64 16 4 2 86, que es igual a la binaria Valor de 01010110. Otra forma de práctica, encontrar el valor binario de esto: 128, 16, 4 y 2 bits están activados, y podemos encontrar el valor binario de 10010110 y el valor decimal de 150. Para memorizar de manera más eficiente, Usted debe practicarlo una y otra vez con valores diferentes en ambos métodos arriba mencionados. La siguiente tabla le ayudará y usted debe memorizarlo. Diagrama de memorización binario a decimal Hex es abreviación de hexadecimal. Este es un sistema de numeración que utiliza las primeras seis letras del alfabeto A a F para ampliar los 10 dígitos accesibles del valor decimal. Por lo tanto, el valor hexadecimal / hexadecimal tiene un total de 16 dígitos. Conversión binaria a decimal y hexadecimal y gráfico de memorización Los valores hexadecimales son totalmente diferentes de los binarios o decimales. Podemos obtener valores hexadecimales mediante la lectura de sólo mordiscos. No es complicado que podemos convertir fácilmente el valor de nibble a hexadecimal. Al principio, debemos entender que el esquema de direccionamiento hexadecimal usa sólo los números de 0 a 9. Mientras que los valores de 10, 11, 12, 13, 14, 15 y 16 no pueden usarse debido a dos dígitos numéricos, por lo que podemos usar Las letras del alfabeto A, B, C, D, E y F en lugar de dos dígitos de números, correspondientemente. Encontrará el valor binario y decimal para cada octeto hexadecimal en la tabla siguiente. Estoy seguro que usted ha notado que los primeros 10 valores hexadecimales 0 a 9 son iguales que los valores decimales. Por ejemplo, si tenemos este valor hexadecimal: 0x9B. Ox frente a cada valor hexadecimal representa que este es un valor hexadecimal y además no tiene ningún otro significado. Debe tener que memorizar que cada carácter hexadecimal es un nibble y dos caracteres hex juntos forman un byte. Para descubrir el valor binario, tenemos que configurar los caracteres hexadecimales en dos nibbles y luego configurarlos juntos en un byte. 9 1001 y B (11 en hex) 1011, por lo que podemos encontrar el byte completo en estos bits 10011011. Y si queremos convertir de binario a hexadecimal, sólo tenemos que romper el byte en pedacitos. Permítanme demostrar, tengo el número binario 10011011. En primer lugar, lo rompo en nibbles 1001 y 1011. En el primer nibble obtengo el valor de 9 ya que los bits 1 y 8 están encendidos, y en el segundo nibble, obtengo el valor De 11 (B en hexadecimal) porque los bits 1, 2 y 8 están activados. Y obtengo el valor hexadecimal 0x9B. Mientras que el valor decimal sería 155, porque el número binario es 10011011, que se convierte a 128 16 8 2 1 155. Hemos cubierto en este artículo que la forma de convertir valores hexadecimales a binarios y decimales de acuerdo con el CCNA 640-802 Cisco Certified Network Associate detalles del curso. Artículo relacionado: ¿Qué es Ethernet Ethernet en el Data Linkhellip Ethernet-II Frame y 802.3 Ethernet Frame Encapsulación y enrutamiento de datos en anhellip Ethernet en la capa física Suscríbase a través de correo electrónico Suscríbase a nuestro boletín para obtener todas las últimas actualizaciones de su bandeja de entrada. Fahad Bin Ali Khilji Learn44 PHP, Programador Java, Desarrollador Web, Ingeniero de Red, Especialista de Seguridad Inter-Red. (Transact-SQL) databasename Es el nombre de la base de datos en la que se crea la tabla (es decir, el nombre de la base de datos en la que se crea la tabla) . Databasename debe especificar el nombre de una base de datos existente. Si no se especifica, databasename por defecto a la base de datos actual. El inicio de sesión para la conexión actual debe estar asociado con un ID de usuario existente en la base de datos especificada por databasename. Y ese ID de usuario debe tener permisos CREATE TABLE. Schemaname Es el nombre del esquema al que pertenece la nueva tabla. Tablename Es el nombre de la nueva tabla. Los nombres de tablas deben seguir las reglas para los identificadores. Tablename puede tener un máximo de 128 caracteres, excepto para los nombres de tabla temporal local (nombres prefijados con un solo signo de número ()) que no pueden exceder los 116 caracteres. AS FileTable Crea la nueva tabla como FileTable. No se especifican columnas porque FileTable tiene un esquema fijo. Para obtener más información acerca de FileTables, vea FileTables (SQL Server). Columnname computedcolumnexpression Es una expresión que define el valor de una columna calculada. Una columna calculada es una columna virtual que no se almacena físicamente en la tabla, a menos que la columna esté marcada como PERSISTED. La columna se calcula a partir de una expresión que utiliza otras columnas de la misma tabla. Por ejemplo, una columna calculada puede tener la definición: cost AS price qty. La expresión puede ser un nombre de columna no controlado, constante, función, variable y cualquier combinación de éstos conectados por uno o más operadores. La expresión no puede ser una subconsulta o contener tipos de datos alias. Las columnas calculadas se pueden utilizar en listas de selección, cláusulas WHERE, cláusulas ORDER BY o cualquier otra ubicación en la que se puedan utilizar expresiones regulares, con las siguientes excepciones: Las columnas calculadas deben marcarse PERSISTED para participar en una restricción FOREIGN KEY o CHECK. Una columna calculada se puede utilizar como columna de clave en un índice o como parte de cualquier restricción PRIMARY KEY o UNIQUE, si el valor de columna calculado está definido por una expresión determinística y el tipo de datos del resultado está permitido en columnas de índice. Por ejemplo, si la tabla tiene columnas enteras a y b. La columna calculada ab puede ser indexada, pero la columna calculada aDATEPART (dd, GETDATE ()) no se puede indexar porque el valor puede cambiar en las invocaciones posteriores. Una columna calculada no puede ser el destino de una instrucción INSERT o UPDATE. Cada fila de una tabla puede tener valores diferentes para las columnas que están involucradas en una columna calculada, por lo tanto, la columna calculada puede no tener el mismo valor para cada fila. En base a las expresiones que se utilizan, la capacidad de anulación de columnas calculadas es determinada automáticamente por el motor de base de datos. El resultado de la mayoría de las expresiones se considera anulable aunque sólo estén presentes columnas no embolsables, ya que los posibles subflujos o desbordamientos también producen resultados NULL. Utilice la función COLUMNPROPERTY con la propiedad AllowsNull para investigar la capacidad de anulación de cualquier columna calculada en una tabla. Una expresión que puede anularse puede convertirse en no anulable especificando ISNULL con la constante de comprobación de expresiones, donde la constante es un valor nonnull sustituido por cualquier resultado NULL. REFERENCIAS se requiere permiso en el tipo para columnas calculadas basadas en expresiones de tipo definido por el usuario de lenguaje común (CLR). PERSISTED Especifica que el motor de base de datos de SQL Server almacenará físicamente los valores calculados en la tabla y actualizará los valores cuando se actualicen otras columnas de las que depende la columna calculada. Marcar una columna calculada como PERSISTED le permite crear un índice en una columna calculada que es determinista, pero no precisa. Para obtener más información, vea Índices en columnas calculadas. Las columnas calculadas que se utilizan como columnas de particionamiento de una tabla particionada deben estar marcadas explícitamente como PERSISTED. Computedcolumnexpression debe ser determinista cuando se especifica PERSISTED. ON filegroup default Especifica el esquema de partición o grupo de archivos en el que se almacena la tabla. Si se especifica ltpartitionschemegt, la tabla debe ser una tabla particionada cuyas particiones se almacenen en un conjunto de uno o más grupos de archivos especificados en ltpartitionschemegt. Si se especifica filegroup, la tabla se almacena en el grupo de archivos named. El grupo de archivos debe existir dentro de la base de datos. Si se especifica por defecto, o si no se especifica en absoluto, la tabla se almacena en el grupo de archivos predeterminado. El mecanismo de almacenamiento de una tabla como se especifica en CREATE TABLE no se puede modificar posteriormente. ON también puede especificarse en una restricción PRIMARY KEY o UNIQUE. Estas restricciones crean índices. Si se especifica filegroup, el índice se almacena en el grupo de archivos con nombre. Si se especifica el valor predeterminado o si no se especifica ON, el índice se almacena en el mismo grupo de archivos que la tabla. Si la restricción PRIMARY KEY o UNIQUE crea un índice agrupado, las páginas de datos de la tabla se almacenan en el mismo grupo de archivos que el índice. Si CLUSTERED se especifica o la restricción crea un índice agrupado, y se especifica un ltpartitionschemegt que difiere del ltpartitionschemegt o grupo de archivos de la definición de tabla, o viceversa, sólo se respetará la definición de restricción y se ignorará la otra. En este contexto, el valor predeterminado no es una palabra clave. Es un identificador para el grupo de archivos predeterminado y debe estar delimitado, como en ON por defecto o por defecto. Si se especifica el valor predeterminado, la opción QUOTEDIDENTIFIER debe estar en ON para la sesión actual. Este es el ajuste predeterminado. Para obtener más información, vea SET QUOTEDIDENTIFIER (Transact-SQL). Después de crear una tabla particionada, considere establecer la opción LOCKESCALATION para la tabla en AUTO. Esto puede mejorar la concurrencia permitiendo que los bloqueos escalen al nivel de partición (HoBT) en lugar de la tabla. Para obtener más información, vea ALTER TABLE (Transact-SQL). TEXTIMAGEON filegroup default Indica que el texto. Ntext. Imagen. Xml. Varchar (máximo). Nvarchar (max). Varbinary (max). Y CLR columnas de tipo definido por el usuario (incluyendo geometría y geografía) se almacenan en el grupo de archivos especificado. TEXTIMAGEON no está permitido si no hay columnas de gran valor en la tabla. TEXTIMAGEON no se puede especificar si se especifica ltpartitionschemegt. Si se especifica por defecto, o si TEXTIMAGEON no se especifica en absoluto, las columnas de gran valor se almacenan en el grupo de archivos predeterminado. El almacenamiento de los datos de columnas de gran valor especificados en CREATE TABLE no puede modificarse posteriormente. Los valores Varchar (max), nvarchar (max), varbinary (max), xml y grandes UDT se almacenan directamente en la fila de datos, hasta un límite de 8000 bytes y siempre que el valor pueda ajustarse al registro. Si el valor no cabe en el registro, un puntero se clasifica en fila y el resto se almacena fuera de fila en el espacio de almacenamiento LOB. 0 es el valor predeterminado. TEXTIMAGEON sólo cambia la ubicación del espacio de almacenamiento LOB, no afecta cuando los datos se almacenan en fila. Utilice tipos de valor grande fuera de la opción de fila de sptableoption para almacenar el valor LOB entero de la fila. En este contexto, el valor predeterminado no es una palabra clave. Es un identificador para el grupo de archivos predeterminado y debe estar delimitado, como en TEXTIMAGEON por defecto o TEXTIMAGEON por defecto. Si se especifica el valor predeterminado, la opción QUOTEDIDENTIFIER debe estar en ON para la sesión actual. Este es el ajuste predeterminado. Para obtener más información, vea SET QUOTEDIDENTIFIER (Transact-SQL). FILESTREAMON partitionschemename filegroup default Especifica el grupo de archivos para los datos FILESTREAM. Si la tabla contiene datos FILESTREAM y la tabla está dividida, debe incluirse la cláusula FILESTREAMON y especificar un esquema de partición de grupos de archivos FILESTREAM. Este esquema de partición debe utilizar la misma partición y columnas de partición como el esquema de partición para la tabla de lo contrario, se genera un error. Si la tabla no está particionada, no se puede particionar la columna FILESTREAM. Los datos FILESTREAM de la tabla deben almacenarse en un único grupo de archivos. Este grupo de archivos se especifica en la cláusula FILESTREAMON. Si la tabla no está particionada y no se especifica la cláusula FILESTREAMON, se utiliza el grupo de archivos FILESTREAM que tiene el conjunto de propiedades DEFAULT. Si no hay grupo de archivos FILESTREAM, se genera un error. Al igual que con ON y TEXTIMAGEON, el valor establecido mediante CREATE TABLE para FILESTREAMON no se puede cambiar, excepto en los siguientes casos: Una sentencia CREATE INDEX convierte un montón en un índice agrupado. En este caso, se puede especificar un grupo de archivos FILESTREAM diferente, un esquema de partición o NULL. Una instrucción DROP INDEX convierte un índice agrupado en un montón. En este caso, se puede especificar un grupo de archivos FILESTREAM diferente, un esquema de partición o un valor predeterminado. El grupo de archivos en la cláusula ltfilegroupgt FILESTREAMON o cada grupo de archivos FILESTREAM que se nombra en el esquema de partición debe tener un archivo definido para el grupo de archivos. Este archivo debe definirse utilizando una sentencia CREATE DATABASE o ALTER DATABASE, de lo contrario se genera un error. Tipo de cambio. Typename Especifica el tipo de datos de la columna y el esquema al que pertenece. Para las tablas basadas en disco, el tipo de datos puede ser uno de los siguientes: Un tipo de datos del sistema. Un tipo de alias basado en un tipo de datos del sistema de SQL Server. Los tipos de datos Alias se crean con la instrucción CREATE TYPE antes de que puedan utilizarse en una definición de tabla. La asignación NULL o NOT NULL para un tipo de datos de alias se puede sobreescribir durante la instrucción CREATE TABLE. Sin embargo, la especificación de longitud no se puede cambiar la longitud de un tipo de datos alias no se puede especificar en una instrucción CREATE TABLE. Un tipo CLR definido por el usuario. Los tipos definidos por el usuario CLR se crean con la instrucción CREATE TYPE antes de que puedan utilizarse en una definición de tabla. Para crear una columna en CLR tipo definido por el usuario, el permiso REFERENCIAS se requiere en el tipo. Si typeschemaname no se especifica, el motor de base de datos de SQL Server hace referencia a typename en el orden siguiente: El tipo de datos del sistema de SQL Server. Esquema predeterminado del usuario actual en la base de datos actual. El esquema dbo en la base de datos actual. Para las tablas optimizadas para la memoria, consulte Tipos de datos compatibles para OLTP en memoria para obtener una lista de los tipos de sistema admitidos. Precision Es la precisión para el tipo de datos especificado. Para obtener más información sobre los valores de precisión válidos, consulte Precisión, Escala y Longitud. Scale Es la escala para el tipo de datos especificado. Para obtener más información sobre valores de escala válidos, consulte Precisión, Escala y Longitud. Max Se aplica sólo al varchar. Nvarchar. Y tipos de datos varbinary para almacenar 231 bytes de caracteres y datos binarios y 230 bytes de datos Unicode. CONTENT Especifica que cada instancia del tipo de datos xml en columnname puede contener varios elementos de nivel superior. CONTENT sólo se aplica al tipo de datos xml y sólo se puede especificar si se especifica xmlschemacollection. Si no se especifica, CONTENIDO es el comportamiento predeterminado. DOCUMENT Especifica que cada instancia del tipo de datos xml en columnname sólo puede contener un elemento de nivel superior. DOCUMENT sólo se aplica al tipo de datos xml y sólo se puede especificar si se especifica xmlschemacollection. Xmlschemacollection Se aplica sólo al tipo de datos xml para asociar una colección de esquema XML con el tipo. Antes de escribir una columna xml en un esquema, primero debe crearse el esquema en la base de datos utilizando CREATE XML SCHEMA COLLECTION. DEFAULT Especifica el valor proporcionado para la columna cuando un valor no se suministra explícitamente durante un inserto. Las definiciones DEFAULT pueden aplicarse a cualquier columna excepto a las definidas como timestamp. O aquellos con la propiedad IDENTITY. Si se especifica un valor predeterminado para una columna de tipo definido por el usuario, el tipo debe admitir una conversión implícita de constantexpression al tipo definido por el usuario. Las definiciones DEFAULT se quitan cuando se abandona la tabla. Sólo un valor constante, como una cadena de caracteres, puede utilizar una función escalar (ya sea un sistema, definida por el usuario o función CLR) o NULL. Para mantener la compatibilidad con versiones anteriores de SQL Server, un nombre de restricción se puede asignar a un DEFAULT. Constantexpression Es una constante, NULL o una función del sistema que se utiliza como valor predeterminado para la columna. Memoryoptimizedconstantexpression Es una constante, NULL, o una función del sistema que se admite en utilizado como valor predeterminado para la columna. Debe tener soporte en procedimientos almacenados compilados nativamente. Para obtener más información acerca de las funciones integradas en los procedimientos almacenados compilados nativamente, consulte Funciones soportadas para módulos T-SQL compilados de forma nativa. IDENTITY Indica que la nueva columna es una columna de identidad. Cuando se agrega una nueva fila a la tabla, el motor de base de datos proporciona un valor incremental único para la columna. Las columnas de identidad suelen utilizarse con restricciones PRIMARY KEY para servir como identificador de fila exclusivo para la tabla. La propiedad IDENTITY se puede asignar a tinyint. Smallint Int Bigint Decimal (p, 0). O columnas numéricas (p, 0). Sólo se puede crear una columna de identidad por tabla. Los valores por defecto predeterminados y las restricciones DEFAULT no se pueden utilizar con una columna de identidad. Tanto la semilla como el incremento o ninguno deben ser especificados. Si no se especifica ninguno, el valor predeterminado es (1,1). En una tabla optimizada para la memoria, el único valor permitido para la semilla y el incremento es 1 (1,1) es el valor por defecto para la semilla y el incremento. Seed Es el valor utilizado para la primera fila cargada en la tabla. Incremento Es el valor incremental agregado al valor de identidad de la fila anterior cargada. NOT FOR REPLICATION En la instrucción CREATE TABLE, se puede especificar la cláusula NOT FOR REPLICATION para la propiedad IDENTITY, restricciones FOREIGN KEY y CHECK. Si se especifica esta cláusula para la propiedad IDENTITY, los valores no se incrementan en las columnas de identidad cuando los agentes de replicación realizan inserciones. Si se especifica esta cláusula para una restricción, la restricción no se aplica cuando los agentes de replicación realizan operaciones de inserción, actualización o eliminación. GENERADO SIEMPRE COMO FILA OCULTADA NO NULO Se aplica a. SQL Server 2016 a través de SQL Server 2016 y base de datos SQL V12. Especifica que una columna datetime2 especificada será utilizada por el sistema para registrar la hora de inicio para la cual un registro es válido o la hora final para la cual un registro es válido. La columna debe definirse como NOT NULL. Si intenta especificarlos como NULL, el sistema lanzará un error. Si no especifica explícitamente NOT NULL para una columna de período, el sistema definirá la columna como NOT NULL de forma predeterminada. Utilice este argumento junto con los argumentos PERIOD FOR SYSTEMTIME y WITH SYSTEMVERSIONING ON para habilitar el control de versiones del sistema en una tabla. Para obtener más información, consulte Tablas temporales. Puede marcar una o ambas columnas de período con el indicador HIDDEN para ocultar de forma implícita estas columnas de forma que SELECT FROM lttablegt no devuelva un valor para esas columnas. De forma predeterminada, las columnas de período no se ocultan. Para poder utilizarlo, las columnas ocultas deben incluirse explícitamente en todas las consultas que hacen referencia directa a la tabla temporal. Para cambiar el atributo HIDDEN para una columna de período existente, PERIOD debe ser eliminado y volver a crear con un distintivo oculto diferente. INDEX indexname CLUSTERED NONCLUSTERED (nombre de columna ASC DESC. N) Especifica crear un índice en la tabla. Esto puede ser un índice agrupado o un índice no agrupado. El índice contendrá las columnas enumeradas y ordenará los datos en orden ascendente o descendente. INDEX indexname CLUSTERED COLUMNSTORE Se aplica a. SQL Server 2016 a través de SQL Server 2016. Especifica para almacenar toda la tabla en formato columnar con un índice de almacén de columnas agrupado. Esto siempre incluye todas las columnas de la tabla. Los datos no se ordenan en orden alfabético o numérico, ya que las filas están organizadas para obtener beneficios de compresión columnstore. INDEX indexname NONCLUSTERED COLUMNSTORE (nombre de columna. N) Se aplica a. SQL Server 2014 a través de SQL Server 2016. Especifica para crear un índice de almacén de columnas no agrupado en la tabla. La tabla subyacente puede ser un montón de filas o un índice agrupado, o puede ser un índice de almacén de columnas agrupado. En todos los casos, la creación de un índice de almacén de columnas no agrupado en una tabla almacena una segunda copia de los datos para las columnas del índice. El índice de almacén de columnas no agrupado se almacena y administra como un índice de almacén de columnas agrupado. Se llama índice de almacén de columnas no agrupado porque las columnas pueden ser limitadas y existe como un índice secundario en una tabla. ON partitionschemename (nombre_columna) Especifica el esquema de partición que define los grupos de archivos en los que se mapearán las particiones de un índice particionado. El esquema de partición debe existir en la base de datos ejecutando ya sea CREATE PARTITION SCHEME o ALTER PARTITION SCHEME. Columnname especifica la columna con la que se particionará un índice particionado. Esta columna debe coincidir con el tipo de datos, la longitud y la precisión del argumento de la función de partición que partitionschemename utiliza. Columnname no está restringido a las columnas de la definición del índice. Se puede especificar cualquier columna de la tabla base, excepto cuando se debe particionar un índice UNIQUE, nombre de columna debe elegirse entre los que se utilizan como clave única. Esta restricción permite al Motor de base de datos verificar la unicidad de los valores clave dentro de una única partición. Al particionar un índice no agrupado, el Motor de base de datos agrega la columna de particionamiento a la lista de claves de índice agrupadas, si no está ya especificada. Al dividir un índice no agrupado no exclusivo, el motor de base de datos agrega la columna de partición como una columna sin clave (incluida) del índice, si no está ya especificada. Si no se especifica partitionschemename o grupo de archivos y la tabla se particiona, el índice se coloca en el mismo esquema de partición, utilizando la misma columna de particionamiento, que la tabla subyacente. No puede especificar un esquema de particionamiento en un índice XML. Si la tabla base está particionada, el índice XML utiliza el mismo esquema de partición que la tabla. Para obtener más información acerca de los índices de partición, tablas e índices particionados. ON filegroupname Crea el índice especificado en el grupo de archivos especificado. Si no se especifica ninguna ubicación y la tabla o vista no está particionada, el índice utiliza el mismo grupo de archivos que la tabla o vista subyacente. El grupo de archivos ya debe existir. ON default Crea el índice especificado en el grupo de archivos predeterminado. El término default, en este contexto, no es una palabra clave. Es un identificador para el grupo de archivos predeterminado y debe estar delimitado, como en ON por defecto o por defecto. Si se especifica el valor predeterminado, la opción QUOTEDIDENTIFIER debe estar en ON para la sesión actual. Este es el ajuste predeterminado. Para obtener más información, vea SET QUOTEDIDENTIFIER (Transact-SQL). FILESTREAMON filestreamfilegroupname partitionschemename NULL Especifica la ubicación de los datos FILESTREAM para la tabla cuando se crea un índice agrupado. La cláusula FILESTREAMON permite que los datos FILESTREAM se muevan a un grupo de archivos o esquema de partición FILESTREAM diferente. Filestreamfilegroupname es el nombre de un grupo de archivos FILESTREAM. El grupo de archivos debe tener un archivo definido para el grupo de archivos utilizando una sentencia CREATE DATABASE o ALTER DATABASE, de lo contrario se genera un error. Si la tabla está particionada, debe incluirse la cláusula FILESTREAMON y debe especificar un esquema de partición de grupos de archivos FILESTREAM que utilice la misma función de partición y las mismas columnas de partición que el esquema de partición de la tabla. De lo contrario, se genera un error. Si la tabla no está particionada, no se puede particionar la columna FILESTREAM. Los datos FILESTREAM de la tabla deben almacenarse en un grupo de archivos especificado en la cláusula FILESTREAMON. FILESTREAMON NULL se puede especificar en una instrucción CREATE INDEX si se está creando un índice agrupado y la tabla no contiene una columna FILESTREAM. ROWGUIDCOL Indica que la nueva columna es una columna GUID de fila. Sólo se puede designar una columna uniqueidentifier por tabla como la columna ROWGUIDCOL. La aplicación de la propiedad ROWGUIDCOL permite referenciar la columna mediante ROWGUID. La propiedad ROWGUIDCOL sólo se puede asignar a una columna uniqueidentifier. Las columnas de tipo de datos definidas por el usuario no se pueden designar con ROWGUIDCOL. La propiedad ROWGUIDCOL no impone la unicidad de los valores almacenados en la columna. ROWGUIDCOL también no genera automáticamente valores para las nuevas filas insertadas en la tabla. Para generar valores únicos para cada columna, utilice la función NEWID o NEWSEQUENTIALID en sentencias INSERT o utilice estas funciones como predeterminadas para la columna. ENCRYPTED WITH Especifica el cifrado de columnas mediante la función Siempre cifrada. COLUMNENCRYPTIONKEY keyname Especifica la clave de cifrado de la columna. Para obtener más información, vea CREATE COLUMN ENCRYPTION KEY (Transact-SQL). ENCRYPTIONTYPE El cifrado determinista utiliza un método que siempre genera el mismo valor cifrado para cualquier valor de texto plano dado. El uso de cifrado determinista permite buscar utilizando comparaciones de igualdad, agrupar y unir tablas utilizando combinaciones de igualdad basadas en valores cifrados, pero también puede permitir que usuarios no autorizados adivinen información sobre valores cifrados examinando patrones en la columna cifrada. La unión de dos tablas a columnas cifradas de forma determinista sólo es posible si ambas columnas están cifradas usando la misma clave de cifrado de columna. El cifrado determinista debe utilizar una intercalación de columnas con un orden de clasificación binario2 para columnas de caracteres. El cifrado aleatorio utiliza un método que cifra los datos de una manera menos predecible. El cifrado aleatorio es más seguro, pero evita búsquedas de igualdad, agrupación y unión en columnas cifradas. Las columnas que utilizan cifrado aleatorio no se pueden indexar. Utilice cifrado determinista para las columnas que serán parámetros de búsqueda o parámetros de agrupación, por ejemplo un número de identificación gubernamental. Utilice cifrado aleatorizado para datos como un número de tarjeta de crédito que no se agrupa con otros registros ni se utiliza para unir tablas y que no se busca porque utiliza otras columnas (por ejemplo, un número de transacción) para encontrar la fila que Contiene la columna cifrada de interés. Las columnas deben ser de un tipo de datos que califique. ALGORITMO Debe ser AEADAES256CBCHMACSHA256. Para obtener más información, incluidas restricciones de entidades, consulte Siempre cifrado (motor de base de datos). Se aplica a . SQL Server 2016 a través de SQL Server 2016. SPARSE Indica que la columna es una columna escasa. The storage of sparse columns is optimized for null values. Sparse columns cannot be designated as NOT NULL. For additional restrictions and more information about sparse columns, see Use Sparse Columns . MASKED WITH ( FUNCTION maskfunction ) Applies to . SQL Server 2016 through SQL Server 2016. Specifies a dynamic data mask. maskfunction is the name of the masking function with the appropriate parameters. Three functions are available: FILESTREAM Valid only for varbinary(max) columns. Specifies FILESTREAM storage for the varbinary(max) BLOB data. The table must also have a column of the uniqueidentifier data type that has the ROWGUIDCOL attribute. This column must not allow null values and must have either a UNIQUE or PRIMARY KEY single-column constraint. The GUID value for the column must be supplied either by an application when inserting data, or by a DEFAULT constraint that uses the NEWID () function. The ROWGUIDCOL column cannot be dropped and the related constraints cannot be changed while there is a FILESTREAM column defined for the table. The ROWGUIDCOL column can be dropped only after the last FILESTREAM column is dropped. When the FILESTREAM storage attribute is specified for a column, all values for that column are stored in a FILESTREAM data container on the file system. COLLATE collationname Specifies the collation for the column. Collation name can be either a Windows collation name or an SQL collation name. collationname is applicable only for columns of the char . varchar . text . nchar . nvarchar . and ntext data types. If not specified, the column is assigned either the collation of the user-defined data type, if the column is of a user-defined data type, or the default collation of the database. For more information about the Windows and SQL collation names, see Windows Collation Name and SQL Collation Name . For more information about the COLLATE clause, see COLLATE (Transact-SQL) . CONSTRAINT Is an optional keyword that indicates the start of the definition of a PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, or CHECK constraint. constraintname Is the name of a constraint. Constraint names must be unique within the schema to which the table belongs. NULL NOT NULL Determine whether null values are allowed in the column. NULL is not strictly a constraint but can be specified just like NOT NULL. NOT NULL can be specified for computed columns only if PERSISTED is also specified. PRIMARY KEY Is a constraint that enforces entity integrity for a specified column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table. UNIQUE Is a constraint that provides entity integrity for a specified column or columns through a unique index. A table can have multiple UNIQUE constraints. CLUSTERED NONCLUSTERED Indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED, and UNIQUE constraints default to NONCLUSTERED. In a CREATE TABLE statement, CLUSTERED can be specified for only one constraint. If CLUSTERED is specified for a UNIQUE constraint and a PRIMARY KEY constraint is also specified, the PRIMARY KEY defaults to NONCLUSTERED. The following shows how to use NONCLUSTERED in a disk-based table: FOREIGN KEY REFERENCES Is a constraint that provides referential integrity for the data in the column or columns. FOREIGN KEY constraints require that each value in the column exists in the corresponding referenced column or columns in the referenced table. FOREIGN KEY constraints can reference only columns that are PRIMARY KEY or UNIQUE constraints in the referenced table or columns referenced in a UNIQUE INDEX on the referenced table. Foreign keys on computed columns must also be marked PERSISTED. schemaname . referencedtablename Is the name of the table referenced by the FOREIGN KEY constraint, and the schema to which it belongs. ( refcolumn , . n ) Is a column, or list of columns, from the table referenced by the FOREIGN KEY constraint. ON DELETE NO ACTION CASCADE SET NULL SET DEFAULT Specifies what action happens to rows in the table created, if those rows have a referential relationship and the referenced row is deleted from the parent table. The default is NO ACTION. NO ACTION The Database Engine raises an error and the delete action on the row in the parent table is rolled back. CASCADE Corresponding rows are deleted from the referencing table if that row is deleted from the parent table. SET NULL All the values that make up the foreign key are set to NULL if the corresponding row in the parent table is deleted. For this constraint to execute, the foreign key columns must be nullable. SET DEFAULT All the values that make up the foreign key are set to their default values if the corresponding row in the parent table is deleted. For this constraint to execute, all foreign key columns must have default definitions. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Do not specify CASCADE if the table will be included in a merge publication that uses logical records. For more information about logical records, see Group Changes to Related Rows with Logical Records . ON DELETE CASCADE cannot be defined if an INSTEAD OF trigger ON DELETE already exists on the table. For example, in the AdventureWorks2012 database, the ProductVendor table has a referential relationship with the Vendor table. The ProductVendor. BusinessEntityID foreign key references the Vendor. BusinessEntityID primary key. If a DELETE statement is executed on a row in the Vendor table, and an ON DELETE CASCADE action is specified for ProductVendor. BusinessEntityID . the Database Engine checks for one or more dependent rows in the ProductVendor table. If any exist, the dependent rows in the ProductVendor table are deleted, and also the row referenced in the Vendor table. Conversely, if NO ACTION is specified, the Database Engine raises an error and rolls back the delete action on the Vendor row if there is at least one row in the ProductVendor table that references it. ON UPDATE NO ACTION CASCADE SET NULL SET DEFAULT Specifies what action happens to rows in the table altered when those rows have a referential relationship and the referenced row is updated in the parent table. The default is NO ACTION. NO ACTION The Database Engine raises an error, and the update action on the row in the parent table is rolled back. CASCADE Corresponding rows are updated in the referencing table when that row is updated in the parent table. SET NULL All the values that make up the foreign key are set to NULL when the corresponding row in the parent table is updated. For this constraint to execute, the foreign key columns must be nullable. SET DEFAULT All the values that make up the foreign key are set to their default values when the corresponding row in the parent table is updated. For this constraint to execute, all foreign key columns must have default definitions. If a column is nullable, and there is no explicit default value set, NULL becomes the implicit default value of the column. Do not specify CASCADE if the table will be included in a merge publication that uses logical records. For more information about logical records, see Group Changes to Related Rows with Logical Records . ON UPDATE CASCADE, SET NULL, or SET DEFAULT cannot be defined if an INSTEAD OF trigger ON UPDATE already exists on the table that is being altered. For example, in the AdventureWorks2012 database, the ProductVendor table has a referential relationship with the Vendor table: ProductVendor. BusinessEntity foreign key references the Vendor. BusinessEntityID primary key. If an UPDATE statement is executed on a row in the Vendor table, and an ON UPDATE CASCADE action is specified for ProductVendor. BusinessEntityID . the Database Engine checks for one or more dependent rows in the ProductVendor table. If any exist, the dependent rows in the ProductVendor table are updated, and also the row referenced in the Vendor table. Conversely, if NO ACTION is specified, the Database Engine raises an error and rolls back the update action on the Vendor row if there is at least one row in the ProductVendor table that references it. CHECK Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns. CHECK constraints on computed columns must also be marked PERSISTED. logicalexpression Is a logical expression that returns TRUE or FALSE. Alias data types cannot be part of the expression. column Is a column or list of columns, in parentheses, used in table constraints to indicate the columns used in the constraint definition. ASC DESC Specifies the order in which the column or columns participating in table constraints are sorted. The default is ASC. partitionschemename Is the name of the partition scheme that defines the filegroups onto which the partitions of a partitioned table will be mapped. The partition scheme must exist within the database. partitioncolumnname . Specifies the column against which a partitioned table will be partitioned. The column must match that specified in the partition function that partitionschemename is using in terms of data type, length, and precision. A computed columns that participates in a partition function must be explicitly marked PERSISTED. We recommend that you specify NOT NULL on the partitioning column of partitioned tables, and also nonpartitioned tables that are sources or targets of ALTER TABLE. SWITCH operations. Doing this makes sure that any CHECK constraints on partitioning columns do not have to check for null values. WITH FILLFACTOR fillfactor Specifies how full the Database Engine should make each index page that is used to store the index data. User-specified fillfactor values can be from 1 through 100. If a value is not specified, the default is 0. Fill factor values 0 and 100 are the same in all respects. Documenting WITH FILLFACTOR fillfactor as the only index option that applies to PRIMARY KEY or UNIQUE constraints is maintained for backward compatibility, but will not be documented in this manner in future releases. columnsetname XML COLUMNSET FOR ALLSPARSECOLUMNS Is the name of the column set. A column set is an untyped XML representation that combines all of the sparse columns of a table into a structured output. For more information about column sets, see Use Column Sets . PERIOD FOR SYSTEMTIME ( systemstarttimecolumnname . systemendtimecolumnname ) Applies to . SQL Server 2016 through SQL Server 2016 and SQL Database V12. Specifies the names of the columns that the system will use to record the period for which a record is valid. Use this argument in conjunction with the GENERATED ALWAYS AS ROW and WITH SYSTEMVERSIONING ON arguments to enable system versioning on a table. For more information, see Temporal Tables . COMPRESSIONDELAY Applies to . SQL Server 2016 through SQL Server 2016. For an in-memory table, delay specifies the minimum number of minutes a row must remain in the table, unchanged, before it is eligible for compression into the columnstore index. SQL Server selects specific rows to compress according to their last update time. For example, if rows are changing frequently during a two-hour period of time, you could set COMPRESSIONDELAY 120 Minutes to ensure updates are completed before SQL Server compresses the row. For a disk-based table, delay specifies the minimum number of minutes a delta rowgroup in the CLOSED state must remain in the delta rowgroup before SQL Server can compress it into the compressed rowgroup. Since disk-based tables dont track insert and update times on individual rows, SQL Server applies the delay to delta rowgroups in the CLOSED state. The default is 0 minutes. lt tableoptiongt. Specifies one or more table options. DATACOMPRESSION Specifies the data compression option for the specified table, partition number, or range of partitions. The options are as follows: NONE Table or specified partitions are not compressed. ROW Table or specified partitions are compressed by using row compression. PAGE Table or specified partitions are compressed by using page compression. COLUMNSTORE Applies to . SQL Server 2016 through SQL Server 2016. Applies only to columnstore indexes, including both nonclustered columnstore and clustered columnstore indexes. COLUMNSTORE specifies to compress with the most performant columnstore compression. This is the typical choice. COLUMNSTOREARCHIVE Applies to . SQL Server 2016 through SQL Server 2016. Applies only to columnstore indexes, including both nonclustered columnstore and clustered columnstore indexes. COLUMNSTOREARCHIVE will further compress the table or partition to a smaller size. This can be used for archival, or for other situations that require a smaller storage size and can afford more time for storage and retrieval. For more information about compression, see Data Compression . ON PARTITIONS ( , . n ) Specifies the partitions to which the DATACOMPRESSION setting applies. If the table is not partitioned, the ON PARTITIONS argument will generate an error. If the ON PARTITIONS clause is not provided, the DATACOMPRESSION option will apply to all partitions of a partitioned table. ltpartitionnumberexpressiongt can be specified in the following ways: Provide the partition number of a partition, for example: ON PARTITIONS (2). Provide the partition numbers for several individual partitions separated by commas, for example: ON PARTITIONS (1, 5). Provide both ranges and individual partitions, for example: ON PARTITIONS (2, 4, 6 TO 8) ltrangegt can be specified as partition numbers separated by the word TO, for example: ON PARTITIONS (6 TO 8). To set different types of data compression for different partitions, specify the DATACOMPRESSION option more than once, for example: ltindexoptiongt. Specifies one or more index options. For a complete description of these options, see CREATE INDEX (Transact-SQL) . PADINDEX OFF When ON, the percentage of free space specified by FILLFACTOR is applied to the intermediate level pages of the index. When OFF or a FILLFACTOR value it not specified, the intermediate level pages are filled to near capacity leaving enough space for at least one row of the maximum size the index can have, considering the set of keys on the intermediate pages. The default is OFF. FILLFACTOR fillfactor Specifies a percentage that indicates how full the Database Engine should make the leaf level of each index page during index creation or alteration. fillfactor must be an integer value from 1 to 100. The default is 0. Fill factor values 0 and 100 are the same in all respects. IGNOREDUPKEY OFF Specifies the error response when an insert operation attempts to insert duplicate key values into a unique index. The IGNOREDUPKEY option applies only to insert operations after the index is created or rebuilt. The option has no effect when executing CREATE INDEX. ALTER INDEX. or UPDATE. The default is OFF. ON A warning message will occur when duplicate key values are inserted into a unique index. Only the rows violating the uniqueness constraint will fail. OFF An error message will occur when duplicate key values are inserted into a unique index. The entire INSERT operation will be rolled back. IGNOREDUPKEY cannot be set to ON for indexes created on a view, non-unique indexes, XML indexes, spatial indexes, and filtered indexes. To view IGNOREDUPKEY, use sys. indexes . In backward compatible syntax, WITH IGNOREDUPKEY is equivalent to WITH IGNOREDUPKEY ON. STATISTICSNORECOMPUTE OFF When ON, out-of-date index statistics are not automatically recomputed. When OFF, automatic statistics updating are enabled. The default is OFF. ALLOWROWLOCKS ON OFF When ON, row locks are allowed when you access the index. The Database Engine determines when row locks are used. When OFF, row locks are not used. The default is ON. ALLOWPAGELOCKS ON OFF When ON, page locks are allowed when you access the index. The Database Engine determines when page locks are used. When OFF, page locks are not used. The default is ON. FILETABLEDIRECTORY directoryname Applies to . SQL Server 2012 through SQL Server 2016. Specifies the windows-compatible FileTable directory name. This name should be unique among all the FileTable directory names in the database. Uniqueness comparison is case-insensitive, regardless of collation settings. If this value is not specified, the name of the filetable is used. FILETABLECOLLATEFILENAME collationname databasedefault Applies to . SQL Server 2012 through SQL Server 2016. Specifies the name of the collation to be applied to the Name column in the FileTable. The collation must be case-insensitive to comply with Windows file naming semantics. If this value is not specified, the database default collation is used. If the database default collation is case-sensitive, an error is raised and the CREATE TABLE operation fails. collationname The name of a case-insensitive collation. databasedefault Specifies that the default collation for the database should be used. This collation must be case-insensitive. FILETABLEPRIMARYKEYCONSTRAINTNAME constraintname Applies to . SQL Server 2012 through SQL Server 2016. Specifies the name to be used for the primary key constraint that is automatically created on the FileTable. If this value is not specified, the system generates a name for the constraint. FILETABLESTREAMIDUNIQUECONSTRAINTNAME constraintname Applies to . SQL Server 2012 through SQL Server 2016. Specifies the name to be used for the unique constraint that is automatically created on the streamid column in the FileTable. If this value is not specified, the system generates a name for the constraint. FILETABLEFULLPATHUNIQUECONSTRAINTNAME constraintname Applies to . SQL Server 2012 through SQL Server 2016. Specifies the name to be used for the unique constraint that is automatically created on the parentpathlocator and name columns in the FileTable. If this value is not specified, the system generates a name for the constraint. SYSTEMVERSIONING ON ( HISTORYTABLE schemaname . historytablename , DATACONSISTENCYCHECK ON OFF ) Applies to . SQL Server 2016 through SQL Server 2016 and SQL Database V12. Enables system versioning of the table if the datatype, nullability constraint, and primary key constraint requirements are met. If the HISTORYTABLE argument is not used, the system generates a new history table matching the schema of the current table in the same filegroup as the current table, creating a link between the two tables and enables the system to record the history of each record in the current table in the history table. The name of this history table will be MSSQLTemporalHistoryForltprimarytableobjectidgt. By default, the history table is PAGE compressed. If the HISTORYTABLE argument is used to create a link to and use an existing history table, the link is created between the current table and the specified table. If current table is partitioned, the history table is created on default file group because partitioning configuration is not replicated automatically from the current table to the history table. If the name of a history table is specified during history table creation, you must specify the schema and table name. When creating a link to an existing history table, you can choose to perform a data consistency check. This data consistency check ensures that existing records do not overlap. Performing the data consistency check is the default. Use this argument in conjunction with the PERIOD FOR SYSTEMTIME and GENERATED ALWAYS AS ROW arguments to enable system versioning on a table. For more information, see Temporal Tables . Creates the new table with Stretch Database enabled or disabled. For more info, see Stretch Database . Enabling Stretch Database for a table When you enable Stretch for a table by specifying ON. you can optionally specify MIGRATIONSTATE OUTBOUND to begin migrating data immediately, or MIGRATIONSTATE PAUSED to postpone data migration. The default value is MIGRATIONSTATE OUTBOUND. For more info about enabling Stretch for a table, see Enable Stretch Database for a table . Prerequisites . Before you enable Stretch for a table, you have to enable Stretch on the server and on the database. For more info, see Enable Stretch Database for a database . Permissions . Enabling Stretch for a database or a table requires dbowner permissions. Enabling Stretch for a table also requires ALTER permissions on the table. FILTERPREDICATE predicate Applies to . SQL Server 2016. Optionally specifies a filter predicate to select rows to migrate from a table that contains both historical and current data. The predicate must call a deterministic inline table-valued function. For more info, see Enable Stretch Database for a table and Select rows to migrate by using a filter predicate (Stretch Database) . If you provide a filter predicate that performs poorly, data migration also performs poorly. Stretch Database applies the filter predicate to the table by using the CROSS APPLY operator. If you dont specify a filter predicate, the entire table is migrated. When you specify a filter predicate, you also have to specify MIGRATIONSTATE . Specify OUTBOUND to migrate data from SQL Server to Azure. Specify INBOUND to copy the remote data for the table from Azure back to SQL Server and to disable Stretch for the table. For more info, see Disable Stretch Database and bring back remote data . This operation incurs data transfer costs, and it cant be canceled. Specify PAUSED to pause or postpone data migration. For more info, see Pause and resume data migration (Stretch Database) . MEMORYOPTIMIZED Applies to . SQL Server 2014 through SQL Server 2016. The value ON indicates that the table is memory optimized. Memory-optimized tables are part of the In-Memory OLTP feature, which is used to optimized the performance of transaction processing. To get started with In-Memory OLTP see Quick Start 1: In-Memory OLTP Technologies for Faster Transact-SQL Performance. For more in-depth information about memory-optimized tables see Memory-Optimized Tables . The default value OFF indicates that the table is disk-based. DURABILITY Applies to . SQL Server 2014 through SQL Server 2016. The value of SCHEMAANDDATA indicates that the table is durable, meaning that changes are persisted on disk and survive restart or failover. SCHEMAANDDATA is the default value. The value of SCHEMAONLY indicates that the table is non-durable. The table schema is persisted but any data updates are not persisted upon a restart or failover of the database. DURABILITYSCHEMAONLY is only allowed with MEMORYOPTIMIZEDON. When a table is created with DURABILITY SCHEMAONLY . and READCOMMITTEDSNAPSHOT is subsequently changed using ALTER DATABASE . data in the table will be lost. BUCKETCOUNT Applies to . SQL Server 2014 through SQL Server 2016. Indicates the number of buckets that should be created in the hash index. The maximum value for BUCKETCOUNT in hash indexes is 1,073,741,824. For more information about bucket counts, see Indexes for Memory-Optimized Tables . Bucketcount is a required argument. INDEX Applies to . SQL Server 2014 through SQL Server 2016. You must specify column and table indexes as part of the CREATE TABLE statement. CREATE INDEX and DROP INDEX are not supported for memory-optimized tables. HASH Applies to . SQL Server 2014 through SQL Server 2016. Indicates that a HASH index is created. Hash indexes are supported only on memory-optimized tables. For information about the number of allowed tables, columns, constraints and indexes, see Maximum Capacity Specifications for SQL Server . Space is generally allocated to tables and indexes in increments of one extent at a time. When the SET MIXEDPAGEALLOCATION option of ALTER DATABASE is set to TRUE, or always prior to SQL Server 2016, when a table or index is created, it is allocated pages from mixed extents until it has enough pages to fill a uniform extent. After it has enough pages to fill a uniform extent, another extent is allocated every time the currently allocated extents become full. For a report about the amount of space allocated and used by a table, execute spspaceused . The Database Engine does not enforce an order in which DEFAULT, IDENTITY, ROWGUIDCOL, or column constraints are specified in a column definition. When a table is created, the QUOTED IDENTIFIER option is always stored as ON in the metadata for the table, even if the option is set to OFF when the table is created. You can create local and global temporary tables. Local temporary tables are visible only in the current session, and global temporary tables are visible to all sessions. Temporary tables cannot be partitioned. Prefix local temporary table names with single number sign ( tablename ), and prefix global temporary table names with a double number sign ( tablename ). SQL statements reference the temporary table by using the value specified for tablename in the CREATE TABLE statement, for example: If more than one temporary table is created inside a single stored procedure or batch, they must have different names. If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, tablename specified for a local temporary name cannot exceed 116 characters. Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped by using DROP TABLE: A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process that called the stored procedure that created the table. All other local temporary tables are dropped automatically at the end of the current session. Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended. A local temporary table created within a stored procedure or trigger can have the same name as a temporary table that was created before the stored procedure or trigger is called. However, if a query references a temporary table and two temporary tables with the same name exist at that time, it is not defined which table the query is resolved against. Nested stored procedures can also create temporary tables with the same name as a temporary table that was created by the stored procedure that called it. However, for modifications to resolve to the table that was created in the nested procedure, the table must have the same structure, with the same column names, as the table created in the calling procedure. This is shown in the following example. constantexpression in a DEFAULT definition cannot refer to another column in the table, or to other tables, views, or stored procedures. DEFAULT definitions cannot be created on columns with a timestamp data type or columns with an IDENTITY property. DEFAULT definitions cannot be created for columns with alias data types if the alias data type is bound to a default object. A column can have any number of CHECK constraints, and the condition can include multiple logical expressions combined with AND and OR. Multiple CHECK constraints for a column are validated in the order they are created. The search condition must evaluate to a Boolean expression and cannot reference another table. A column-level CHECK constraint can reference only the constrained column, and a table-level CHECK constraint can reference only columns in the same table. CHECK CONSTRAINTS and rules serve the same function of validating the data during INSERT and UPDATE statements. When a rule and one or more CHECK constraints exist for a column or columns, all restrictions are evaluated. CHECK constraints cannot be defined on text . ntext . or image columns. An index created for a constraint cannot be dropped by using DROP INDEX the constraint must be dropped by using ALTER TABLE. An index created for and used by a constraint can be rebuilt by using ALTER INDEX. REBUILD. For more information, see Reorganize and Rebuild Indexes . Constraint names must follow the rules for identifiers. except that the name cannot start with a number sign (). If constraintname is not supplied, a system-generated name is assigned to the constraint. The constraint name appears in any error message about constraint violations. When a constraint is violated in an INSERT, UPDATE, or DELETE statement, the statement is ended. However, when SET XACTABORT is set to OFF, the transaction, if the statement is part of an explicit transaction, continues to be processed. When SET XACTABORT is set to ON, the whole transaction is rolled back. You can also use the ROLLBACK TRANSACTION statement with the transaction definition by checking the ERROR system function. When ALLOWROWLOCKS ON and ALLOWPAGELOCK ON, row-, page-, and table-level locks are allowed when you access the index. The Database Engine chooses the appropriate lock and can escalate the lock from a row or page lock to a table lock. When ALLOWROWLOCKS OFF and ALLOWPAGELOCK OFF, only a table-level lock is allowed when you access the index. If a table has FOREIGN KEY or CHECK CONSTRAINTS and triggers, the constraint conditions are evaluated before the trigger is executed. For a report on a table and its columns, use sphelp or sphelpconstraint . To rename a table, use sprename . For a report on the views and stored procedures that depend on a table, use sys. dmsqlreferencedentities and sys. dmsqlreferencingentities . The nullability of a column determines whether that column can allow a null value (NULL) as the data in that column. NULL is not zero or blank: NULL means no entry was made or an explicit NULL was supplied, and it typically implies that the value is either unknown or not applicable. When you use CREATE TABLE or ALTER TABLE to create or alter a table, database and session settings influence and possibly override the nullability of the data type that is used in a column definition. We recommend that you always explicitly define a column as NULL or NOT NULL for noncomputed columns or, if you use a user-defined data type, that you allow the column to use the default nullability of the data type. Sparse columns must always allow NULL. When column nullability is not explicitly specified, column nullability follows the rules shown in the following table. Column data type Alias data type The Database Engine uses the nullability that is specified when the data type was created. To determine the default nullability of the data type, use sphelp . CLR user-defined type Nullability is determined according to the column definition. System-supplied data type If the system-supplied data type has only one option, it takes precedence. timestamp data types must be NOT NULL. When any session settings are set ON by using SET: ANSINULLDFLTON ON, NULL is assigned. ANSINULLDFLTOFF ON, NOT NULL is assigned. When any database settings are configured by using ALTER DATABASE: ANSINULLDEFAULTON ON, NULL is assigned. ANSINULLDEFAULTOFF ON, NOT NULL is assigned. To view the database setting for ANSINULLDEFAULT, use the sys. databases catalog view When neither of the ANSINULLDFLT options is set for the session and the database is set to the default (ANSINULLDEFAULTis OFF), the default of NOT NULL is assigned. If the column is a computed column, its nullability is always automatically determined by the Database Engine. To find out the nullability of this type of column, use the COLUMNPROPERTY function with the AllowsNull property. The SQL Server ODBC driver and Microsoft OLE DB Provider for SQL Server both default to having ANSINULLDFLTON set to ON. ODBC and OLE DB users can configure this in ODBC data sources, or with connection attributes or properties set by the application. I. Using the uniqueidentifier data type in a column The following example creates a table with a uniqueidentifier column. The example uses a PRIMARY KEY constraint to protect the table against users inserting duplicated values, and it uses the NEWSEQUENTIALID() function in the DEFAULT constraint to provide values for new rows. The ROWGUIDCOL property is applied to the uniqueidentifier column so that it can be referenced using the ROWGUID keyword. For additional data compression examples, see Data Compression . O. Creating a table that has sparse columns and a column set The following examples show to how to create a table that has a sparse column, and a table that has two sparse columns and a column set. The examples use the basic syntax. For more complex examples, see Use Sparse Columns and Use Column Sets . This example creates a table that has a sparse column.
No comments:
Post a Comment