SQL Server
SQL Server
Anterior Siguiente
Sintaxis
CREATE DATABASE databasename;
Ejemplo
CREATE DATABASE testDB;
Nota: Tenga cuidado antes de dejar caer una base de datos. Al eliminar
una base de datos se perder toda la informacin almacenada en la base
de datos.
Ejemplo
DROP DATABASE testDB;
Sintaxis
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
Los parmetros de columna especifican los nombres de las columnas de
la tabla.
Ejemplo
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
Intntalo t mismo "
Si crea una nueva tabla utilizando una tabla existente, la nueva tabla se
rellenar con los valores existentes de la tabla antigua.
Sintaxis
CREATE TABLE new_table_name AS
SELECT column1, column2,...
FROM existing_table_name
WHERE ....;
Sintaxis
DROP TABLE table_name;
Nota : Tenga cuidado antes de dejar caer una mesa. Eliminar una
tabla resultar en la prdida de informacin completa
almacenada en la tabla!
Sintaxis
TRUNCATE TABLE table_name;
Restricciones de SQL
Anterior Siguiente
Las restricciones SQL se utilizan para especificar reglas para datos en
una tabla.
Sintaxis
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
Restricciones de SQL
Las restricciones de SQL se utilizan para especificar reglas para los datos
de una tabla.
Ejemplo
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255) NOT NULL,
Age int
);
Sin embargo, puede tener muchas restricciones UNIQUE por tabla, pero
slo una restriccin PRIMARY KEY por tabla.
MySQL:
MySQL:
Una tabla puede tener slo una clave primaria, que puede consistir en
campos nicos o mltiples.
MySQL:
MySQL:
Tabla "Personas":
1 Hansen Ola 3
2 Svendson Tove 2
3 Pettersen Kari 2
Tabla "Pedidos":
1 77895 3
2 44678 3
3 22456 2
4 24562 1
MySQL:
MySQL:
MySQL:
MySQL:
MySQL:
Orculo:
ALTER TABLE Persons
MODIFY City DEFAULT 'Sandnes';
MySQL:
Nota: Actualizar una tabla con ndices lleva ms tiempo que actualizar
una tabla sin (porque los ndices tambin necesitan una
actualizacin). Por lo tanto, slo cree ndices en las columnas que se
buscarn frecuentemente.
MS Access:
Servidor SQL:
DB2 / Oracle:
Fechas SQL
La parte ms difcil al trabajar con fechas es asegurarse de que el
formato de la fecha que intenta insertar coincide con el formato de la
columna de fecha en la base de datos.
SQL Server incluye los siguientes tipos de datos para almacenar una
fecha o un valor de fecha / hora en la base de datos:
Nota: Los tipos de fecha se eligen para una columna cuando se crea
una nueva tabla en la base de datos!
1 Geitost 2008-11-11
1 Geitost 2008-11-11
Vistas SQL
Anterior Siguiente
Una vista contiene filas y columnas, al igual que una tabla real. Los
campos de una vista son campos de una o ms tablas reales de la base
de datos.
Inyeccin de SQL
Anterior Siguiente
Inyeccin SQL
La inyeccin SQL es una tcnica de inyeccin de cdigo que puede
destruir su base de datos.
Ejemplo
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Identidad de usuario:
SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;
Nombre de usuario:
Contrasea:
Ejemplo
uName = getRequestString("username");
uPass = getRequestString("userpassword");
sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' +
uPass + '"'
Resultado
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"
Nombre de usuario:
Contrasea:
Resultado
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""
Ejemplo
SELECT * FROM Users; DROP TABLE Suppliers
Ejemplo
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;
Y la siguiente entrada:
Identidad de usuario:
Resultado
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;
Utilizar parmetros de SQL para la
proteccin
Para proteger un sitio web de la inyeccin de SQL, puede utilizar
parmetros de SQL.
Los parmetros SQL son valores que se agregan a una consulta SQL en
tiempo de ejecucin, de forma controlada.
Otro ejemplo
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);
Ejemplos
Los siguientes ejemplos muestran cmo generar consultas
parametrizadas en algunos idiomas web comunes.
txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City)
Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();
Alojamiento de SQL
Anterior Siguiente
Alojamiento de SQL
Si desea que su sitio web pueda almacenar y recuperar datos de una
base de datos, su servidor web debe tener acceso a un sistema de base
de datos que utilice el lenguaje SQL.
Orculo
Oracle tambin es un popular software de base de datos para sitios web
con base de datos y con alto trfico.
MySQL
MySQL tambin es un popular software de base de datos para sitios
web.
Acceso
Cuando un sitio web requiere slo una base de datos simple, Microsoft
Access puede ser una solucin.
Function Description
ASCII Returns the number code that represents the specific characte
Function Description
CEILING Returns the smallest integer value that is greater than or equa
number
FLOOR Returns the largest integer value that is equal to or less than
Function Description
DATEADD Returns a date after a certain time/date interval has been add
DATEDIFF Returns the difference between two date values, based on the
specified
DAY Returns the day of the month (from 1 to 31) for a given date
YEAR Returns the year (as a four-digit number) for a given date
Function Description
CURRENT_USER Returns the name of the current user in the SQL Server datab
SESSION_USER Returns the user name of the current session in the SQL Serve
SYSTEM_USER Returns the login name information for the current user in the
Server database
VARCHAR(size) Holds a variable length string (can contain letters, numbers, and special characters). Th
size is specified in parenthesis. Can store up to 255 characters. Note: If you put a greate
255 it will be converted to a TEXT type
BLOB For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(x,y,z,etc.) Let you enter a list of possible values. You can list up to 65535 values in an ENUM list. If
inserted that is not in the list, a blank value will be inserted.
Note: The values are sorted in the order you enter them.
TINYINT(size) -128 to 127 normal. 0 to 255 UNSIGNED*. The maximum number of digits may be spec
parenthesis
SMALLINT(size) -32768 to 32767 normal. 0 to 65535 UNSIGNED*. The maximum number of digits may
parenthesis
FLOAT(size,d) A small number with a floating decimal point. The maximum number of digits may be s
size parameter. The maximum number of digits to the right of the decimal point is spec
parameter
DOUBLE(size,d) A large number with a floating decimal point. The maximum number of digits may be s
size parameter. The maximum number of digits to the right of the decimal point is spec
parameter
DECIMAL(size,d) A DOUBLE stored as a string , allowing for a fixed decimal point. The maximum number
be specified in the size parameter. The maximum number of digits to the right of the d
specified in the d parameter
text Variable width character string 2GB of text data 4 bytes + numb
The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. Default value is 0
The p parameter indicates the maximum total number of digits that can be stored
(both to the left and to the right of the decimal point). p must be a value from 1 to
38. Default is 18.
The s parameter indicates the maximum number of digits stored to the right of
the decimal point. s must be a value from 0 to p. Default value is 0
float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308.
The n parameter indicates whether the field should hold 4 or 8 bytes. float(24)
holds a 4-byte field and float(53) holds an 8-byte field. Default value of n is 53.
datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds
datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds
date Store a date only. From January 1, 0001 to December 31, 9999
datetimeoffset The same as datetime2 with the addition of a time zone offset
timestamp Stores a unique number that gets updated every time a row gets created or modified.
The timestamp value is based upon an internal clock and does not correspond to real
time. Each table may have only one timestamp variable
sql_variant Stores up to 8,000 bytes of data of various data types, except text
timestamp
Text Use for text or combinations of text and numbers. 255 characters maximum
Memo Memo is used for larger amounts of text. Stores up to 65,536 characters. Note: You
cannot sort a memo field. However, they are searchable
AutoNumber AutoNumber fields automatically give each record its own number, usually starting at 1
Yes/No A logical field can be displayed as Yes/No, True/False, or On/Off. In code, use the
constants True and False (equivalent to -1 and 0). Note: Null values are not allowed in
Yes/No fields
Ole Object Can store pictures, audio, video, or other BLOBs (Binary Large OBjects)
Lookup Wizard Let you type a list of options, which can then be chosen from a drop-down list
or
or
SELECT column_name
FROM table_name AS table_alias
or
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
or
SELECT * SELECT *
FROM table_name
or
SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name