Вы находитесь на странице: 1из 38

Adding Files to Filegroup

USE [master] GO ALTER DATABASE MyDatabase ADD FILEGROUP Group2 GO ALTER DATABASE MyDatabase ADD FILE ( NAME = Second_DataFile, FILENAME = 'C:\DATA\mydat2.ndf', SIZE = 600KB, MAXSIZE = 800KB, FILEGROWTH = 25KB ) TO FILEGROUP Group2; GO

Data Types
Integers
bigint Integer (whole number) data from -2^63 (9,223,372,036,854,775,808) through 2^63-1 (9,223,372,036,854,775,807). int Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). smallint Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). tinyint Integer data from 0 through 255. bit Integer data with either a 1 or 0 value.

Money and smallmoney money Monetary data values from -2^63 (922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. smallmoney Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit.

Decimal Numerics
float Floating precision number data with the following valid values: -1.79E + 308 through -2.23E - 308, 0 and 2.23E + 308 through 1.79E + 308. real Floating precision number data with the following valid values: -3.40E + 38 through -1.18E - 38, 0 and 1.18E - 38 through 3.40E + 38.

Datetime and smalldatetime


datetime Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds. smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.

Character Strings
char Fixed-length non-Unicode character data with a maximum length of 8,000 characters. varchar Variable-length non-Unicode data with a maximum of 8,000 characters. text Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters.

Unicode Character Strings


nchar Fixed-length Unicode data with a maximum length of 4,000 characters. nvarchar Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied user-defined data type that is functionally equivalent to nvarchar(128)and is used to reference database object names. ntext Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.

Binary Strings
binary Fixed-length binary data with a maximum length of 8,000 bytes. varbinary Variable-length binary data with a maximum length of 8,000 bytes. image Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.

Other Data Types


cursor A reference to a cursor. sql_variant A data type that stores values of various SQL Server-supported data types, except text, ntext, timestamp, and sql_variant. table A special data type used to store a result set for later processing .

timestamp A database-wide unique number that gets updated every time a row gets updated. uniqueidentifier A globally unique identifier (GUID).

Creating Table
CREATE TABLE Persons ( P_Id int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) )

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

SQL UNIQUE Constraint


The UNIQUE constraint uniquely identifies each record in a database table. The UNIQUE and PRIMARY KEY constraints both provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint defined on it. Note that you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.

CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName) )

SQL UNIQUE Constraint on ALTER TABLE


To create a UNIQUE constraint on the "P_Id" column when the table is already created, use the following SQL:

ALTER TABLE Persons ADD UNIQUE (P_Id)


To allow naming of a UNIQUE constraint, and for defining a UNIQUE constraint on multiple columns, use the following SQL syntax:

ALTER TABLE Persons ADD CONSTRAINT uc_PersonID UNIQUE (P_Id,LastName)

To DROP a UNIQUE Constraint


ALTER TABLE Persons DROP CONSTRAINT uc_PersonID

Primary Key
CREATE TABLE Persons ( P_Id int NOT NULL PRIMARY KEY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName) ) ALTER TABLE Persons ADD PRIMARY KEY (P_Id)

ALTER TABLE Persons DROP PRIMARY KEY

SQL FOREIGN KEY Constraint


A FOREIGN KEY in one table points to a PRIMARY KEY in another table. The "Persons" table: P_Id 1 2 LastName Hansen Svendson FirstName Ola Tove Address Borgvn 23 City Sandnes Timoteivn 10 Sandnes

Pettersen

Kari

Storgt 20

Stavanger

The "Orders" table:


O_Id 1 2 3 4 OrderNo 77895 44678 22456 24562 P_Id 3 3 2 1

Note that the "P_Id" column in the "Orders" table points to the "P_Id" column in the "Persons" table. The "P_Id" column in the "Persons" table is the PRIMARY KEY in the "Persons" table. The "P_Id" column in the "Orders" table is a FOREIGN KEY in the "Orders" table. The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, PRIMARY KEY (O_Id), CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id) REFERENCES Persons(P_Id) ) ALTER TABLE Orders DROP CONSTRAINT fk_PerOrders

Check
CREATE TABLE Persons ( P_Id int NOT NULL, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255), CONSTRAINT chk_Person CHECK (P_Id>0 AND City='Sandnes') )

SQL DEFAULT Constraint


The DEFAULT constraint is used to insert a default value into a column. The default value will be added to all new records, if no other value is specified.
CREATE TABLE Orders ( O_Id int NOT NULL, OrderNo int NOT NULL, P_Id int, OrderDate date DEFAULT GETDATE() )

ALTER TABLE Persons ALTER COLUMN City SET DEFAULT 'SANDNES

Indexes
Indexes allow the database application to find data fast; without reading the whole table. An index can be created in a table to find data more quickly and efficiently. The users cannot see the indexes, they are just used to speed up searches/queries. Updating a table with indexes takes more time than updating a table without (because the indexes also need an update). So you should only create indexes on columns (and tables) that will be frequently searched against.

Creates an index on a table. Duplicate values are allowed: CREATE INDEX PIndex ON Persons (LastName) CREATE INDEX PIndex ON Persons (LastName, FirstName)
Creates a unique index on a table. Duplicate values are not allowed: CREATE UNIQUE INDEX PIndex ON Persons (LastName)

Droping a index
DROP INDEX table_name.index_name

Alter Table
ALTER TABLE Persons ADD DateOfBirth date ALTER TABLE Persons ALTER COLUMN DateOfBirth year ALTER TABLE Persons DROP COLUMN DateOfBirth

AUTO INCREMENT Field


The MS SQL Server uses the IDENTITY keyword to perform an auto-increment feature. The following SQL statement defines the "P_Id" column to be an auto-increment primary key field in the "Persons" table: CREATE TABLE Persons ( P_Id int PRIMARY KEY IDENTITY, LastName varchar(255) NOT NULL, FirstName varchar(255), Address varchar(255), City varchar(255) )

CREATE TABLE mytable ( low int, high int, myavg AS (low + high)/2 ) INSERT INTO mytable(low,high) VALUES(10,15)
select * from mytable drop table mytable CREATE TABLE mytable ( low int, high int, myavg AS ((Convert(float,low) + high)/2) )

By default, the starting value for IDENTITY is 1, and it will increment by 1 for each new record. To specify that the "P_Id" column should start at value 10 and increment by 5, change the identity to IDENTITY(10,5). To insert a new record into the "Persons" table, we will not have to specify a value for the "P_Id" column (a unique value will be added automatically) INSERT INTO Persons (FirstName,LastName) VALUES ('Lars','Monsen')

CREATE VIEW
In SQL, a view is a virtual table based on the result-set of an SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. CREATE VIEW view_name AS SELECT column_name(s) FROM table_name WHERE condition DROP VIEW view_name

SQL Date Functions


Function GETDATE() DATEPART()
DATEADD() DATEDIFF() CONVERT()

Description Returns the current date and time Returns a single part of a date/time Adds or subtracts a specified time interval from a date Returns the time between two dates Displays date/time data in different formats

SQL Server comes with the following data types for storing a date or a date/time value in the database: SELECT GETDATE() AS CurrentDateTime DATE - format YYYY-MM-DD DATETIME - format: YYYY-MM-DD HH:MM:SS SMALLDATETIME - format: YYYY-MM-DD HH:MM:SS TIMESTAMP - format: a unique number

CREATE TABLE Orders ( OrderId int NOT NULL PRIMARY KEY, ProductName varchar(50) NOT NULL, OrderPrice int, OrderDate datetime NOT NULL DEFAULT GETDATE() ) INSERT INTO Orders (OrderId,ProductName,OrderPrice) VALUES (4,'Jarlsberg Cheese,500)
OrderId 1 2 3 4 ProductName Geitost Camembert Pierrot Mozzarella di Giovanni Mascarpone Fabioli OrderDate 2008-11-11 2008-11-09 2008-11-11 2008-10-29 OrderPrice 500 200 100 400

SELECT * FROM Orders WHERE OrderDate='2008-11-11' SELECT AVG(OrderPrice) AS OrderAverage FROM Orders SELECT Customer FROM Orders WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders)

SQL NULL Values


NULL values represent missing unknown data. By default, a table column can hold NULL values. SELECT LastName,FirstName,Address FROM Persons WHERE Address IS NULL

SQL Aggregate Functions


SQL aggregate functions return a single value, calculated from values in a column. AVG() - Returns the average value COUNT() - Returns the number of rows FIRST() - Returns the first value LAST() - Returns the last value MAX() - Returns the largest value MIN() - Returns the smallest value SUM() - Returns the sum

SQL Scalar functions


SQL scalar functions return a single value, based on the input value. Useful scalar functions:
UCASE() - Converts a field to upper case LCASE() - Converts a field to lower case MID() - Extract characters from a text field LEN() - Returns the length of a text field ROUND() - Rounds a numeric field to the number of decimals specified NOW() - Returns the current system date and time FORMAT() - Formats how a field is to be displayed

O_Id 1 2 3 4 5 6

OrderDate 2008/11/12 2008/10/23 2008/09/02 2008/09/03 2008/08/30 2008/10/04

OrderPrice 1000 1600 700 300 2000 100

Customer Hansen Nilsen Hansen Hansen Jensen Nilsen

SELECT AVG(OrderPrice) AS OrderAverage FROM Orders

Nested(Inner) Query
SELECT Customer FROM Orders WHERE OrderPrice>(SELECT AVG(OrderPrice) FROM Orders
Customer Hansen Nilsen Jensen

COUNT() Function
The COUNT() function returns the number of rows that matches a specified criteria. The COUNT(column_name) function returns the number of values (NULL values will not be counted) of the specified column: SELECT COUNT(column_name) FROM table_name The COUNT(*) function returns the number of records in a table: SELECT COUNT(*) FROM table_name

IN Operator
The IN operator allows you to specify multiple values in a WHERE clause
_Id 1 2 3 LastName FirstName Address Hansen Ola Timoteivn 10 Svendson Tove Borgvn 23 Pettersen Kari Storgt 20 City Sandnes Sandnes Stavanger

SELECT * FROM Persons WHERE LastName IN ('Hansen','Pettersen')


P_Id 1 3 LastName Hansen Pettersen FirstName Ola Kari Address Timoteivn 10 Storgt 20 City Sandnes Stavanger

Between Operator
SELECT * FROM Persons WHERE LastName BETWEEN 'Hansen' AND 'Pettersen'

Вам также может понравиться