SQL Server/T-SQL Tutorial/View/View — различия между версиями

Материал из SQL эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 13:46, 26 мая 2010

Create and query a view

5> CREATE TABLE Customers (
6>      CustomerID nchar (5) NOT NULL ,
7>      CompanyName nvarchar (40) NOT NULL ,
8>      ContactName nvarchar (30) NULL ,
9>      ContactTitle nvarchar (30) NULL ,
10>     Address nvarchar (60) NULL ,
11>     City nvarchar (15) NULL ,
12>     Region nvarchar (15) NULL ,
13>     PostalCode nvarchar (10) NULL ,
14>     Country nvarchar (15) NULL ,
15>     Phone nvarchar (24) NULL ,
16>     Fax nvarchar (24) NULL
17> )
18> GO
1>
2> INSERT Customers VALUES("1","A","Maria",    "Sales",  "Str. 57", "Berlin"    ,NULL,"12209", "Germany","111-1111111","111-1111111")
3> INSERT Customers VALUES("2","M","Joe",      "Owner",  "Ave. 231","Vancouver" ,NULL,"05023", "Mexico", "(222) 222-3332",NULL)
4> INSERT Customers VALUES("3","H","Thomas",   "Sales",  "Sq.  111","London"    ,NULL,"1D00P", "UK",     "(444) 444-4444","(444) 444-4444")
5> INSERT Customers VALUES("4","B","Berg",     "Order",  "Blv    8","Toronto"   ,NULL,"00222", "Sweden", "4444-55 55 65","5555-55 55 55")
6> INSERT Customers VALUES("5","S","Moos",     "Sales",  "Fort  57","New York"  ,NULL,"68306", "Germany","6666-66666","6666-77777")
7> INSERT Customers VALUES("6","F","Cite",     "Manager","24      ","Dalles"    ,NULL,"67000", "France", "88.60.15.31","88.60.15.32")
8> INSERT Customers VALUES("7","C","Sommer",   "Owner",  "Araq, 67","Paris"     ,NULL,"28023", "Spain",  "(91) 555 22 82","(91) 555 91 99")
9> INSERT Customers VALUES("8","P","Leb",      "Owner",  "12      ","Beijing"   ,NULL,"13008", "France", "91.24.45.40","91.24.45.41")
10> INSERT Customers VALUES("9","D","Elizabeth","Manager","23 Blvd.","Tsawassen","BC", "T2F8M4","Canada", "(604) 555-4729","(604) 555-3745")
11> go
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2>
3>    CREATE VIEW CustomerPhoneList_vw
4>    AS
5>       SELECT CustomerID
6>       FROM Customers
7> GO
1>
2>    SELECT * FROM CustomerPhoneList_vw
3> GO
CustomerID
----------
1
2
3
4
5
6
7
8
9
(9 rows affected)
1>    SELECT * FROM Customers
2> GO
CustomerID CompanyName                              ContactName                    ContactTitle                   Address                                                      City            Region
       PostalCode Country         Phone                    Fax
---------- ---------------------------------------- ------------------------------ ------------------------------ ------------------------------------------------------------ --------------- ---------
------ ---------- --------------- ------------------------ ------------------------
1          A                                        Maria                          Sales                          Str. 57                                                      Berlin          NULL
       12209      Germany         111-1111111              111-1111111
2          M                                        Joe                            Owner                          Ave. 231                                                     Vancouver       NULL
       05023      Mexico          (222) 222-3332           NULL
3          H                                        Thomas                         Sales                          Sq.  111                                                     London          NULL
       1D00P      UK              (444) 444-4444           (444) 444-4444
4          B                                        Berg                           Order                          Blv    8                                                     Toronto         NULL
       00222      Sweden          4444-55 55 65            5555-55 55 55
5          S                                        Moos                           Sales                          Fort  57                                                     New York        NULL
       68306      Germany         6666-66666               6666-77777
6          F                                        Cite                           Manager                        24                                                           Dalles          NULL
       67000      France          88.60.15.31              88.60.15.32
7          C                                        Sommer                         Owner                          Araq, 67                                                     Paris           NULL
       28023      Spain           (91) 555 22 82           (91) 555 91 99
8          P                                        Leb                            Owner                          12                                                           Beijing         NULL
       13008      France          91.24.45.40              91.24.45.41
9          D                                        Elizabeth                      Manager                        23 Blvd.                                                     Tsawassen       BC
       T2F8M4     Canada          (604) 555-4729           (604) 555-3745
(9 rows affected)
1>
2> drop view CustomerPhoneList_vw;
3> GO
1>
2> drop table Customers;
3> GO
1>


Create a view to wrap a long sql statement

2>
3> CREATE TABLE authors(
4>    au_id          varchar(11),
5>    au_lname       varchar(40)       NOT NULL,
6>    au_fname       varchar(20)       NOT NULL,
7>    phone          char(12)          NOT NULL DEFAULT ("UNKNOWN"),
8>    address        varchar(40)           NULL,
9>    city           varchar(20)           NULL,
10>    state          char(2)               NULL,
11>    zip            char(5)               NULL,
12>    contract       bit               NOT NULL
13> )
14> GO
1> insert authors values("1",  "Joe",   "Abra",   "111 111-1111", "6 St.", "Berkeley",  "CA", "11111", 1)
2> insert authors values("2",  "Jack",  "Majo",   "222 222-2222", "3 St.", "Oakland" ,  "CA", "22222", 1)
3> insert authors values("3",  "Pink",  "Cherry", "333 333-3333", "5 Ln.", "Vancouver", "BC", "33333", 1)
4> insert authors values("4",  "Blue",  "Albert", "444 444-4444", "7 Av.", "Vancouver", "BC", "44444", 1)
5> insert authors values("5",  "Red",   "Anne",   "555 555-5555", "6 Av.", "Regina",    "SK", "55555", 1)
6> insert authors values("6",  "Black", "Michel", "666 666-6666", "3 Pl.", "Regina",    "SK", "66666", 1)
7> insert authors values("7",  "White", "Sylvia", "777 777-7777", "1 Pl.", "Rockville", "MD", "77777", 1)
8> insert authors values("8",  "Yellow","Heather","888 888-8888", "3 Pu",  "Vacaville", "CA", "88888", 0)
9> insert authors values("9",  "Gold",  "Dep",    "999 999-9999", "5 Av.", "Oakland",   "CA", "99999", 0)
10> insert authors values("10", "Siler", "Dean",   "000 000-0000", "4 Av.", "Oakland",   "CA", "00000", 1)
11> GO
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2> CREATE TABLE titleauthor(
3>    au_id          varchar(20),
4>    title_id       varchar(20),
5>    au_ord         tinyint               NULL,
6>    royaltyper     int                   NULL
7> )
8> GO
1>
2> insert titleauthor values("1", "2", 1, 60)
3> insert titleauthor values("2", "3", 1, 100)
4> insert titleauthor values("3", "4", 1, 100)
5> insert titleauthor values("4", "5", 1, 100)
6> insert titleauthor values("5", "6", 1, 100)
7> insert titleauthor values("6", "7", 2, 40)
8> insert titleauthor values("7", "8", 1, 100)
9> insert titleauthor values("8", "9", 1, 100)
10> GO
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2> CREATE TABLE sales(
3>    stor_id        char(4)           NOT NULL,
4>    ord_num        varchar(20)       NOT NULL,
5>    ord_date       datetime          NOT NULL,
6>    qty            smallint          NOT NULL,
7>    payterms       varchar(12)       NOT NULL,
8>    title_id       varchar(80)
9> )
10> GO
1> insert sales values("1", "QA7442.3", "09/13/94", 75, "ON Billing","1")
2> insert sales values("2", "D4482",    "09/14/94", 10, "Net 60",    "1")
3> insert sales values("3", "N914008",  "09/14/94", 20, "Net 30",    "2")
4> insert sales values("4", "N914014",  "09/14/94", 25, "Net 30",    "3")
5> insert sales values("5", "423LL922", "09/14/94", 15, "ON Billing","3")
6> insert sales values("6", "423LL930", "09/14/94", 10, "ON Billing","2")
7> GO
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2>
3>
4>    --CREATE our view
5>    CREATE VIEW vSalesCount
6>    AS
7>       SELECT au.au_id,
8>           au.au_lname + ", " + au.au_fname AS au_name, au.address,
9>           au.city + ", " + au.state + " " + zip AS address2,
10>           SUM(s.qty) As SalesCount
11>       FROM authors au
12>       JOIN titleauthor ta
13>           ON au.au_id = ta.au_id
14>       JOIN sales s
15>           ON ta.title_id = s.title_id
16>       GROUP BY au.au_id,
17>           au.au_lname + ", " + au.au_fname,
18>           au.address,
19>           au.city + ", " + au.state + " " + zip
20>    GO
1>
2>
3>    SELECT au_name, address, Address2 FROM vSalesCount
4>    WHERE SalesCount > 25
5> GO
au_name                                                        address                                  Address2
-------------------------------------------------------------- ---------------------------------------- ------------------------------
Joe, Abra                                                      6 St.                                    Berkeley, CA 11111
Jack, Majo                                                     3 St.                                    Oakland, CA 22222
(2 rows affected)
1>
2> drop view vSalesCount;
3> GO
1>
2> drop table authors;
3> GO
1> drop table titleauthor;
2> drop table sales;
3> GO
1>
2>


Join syscomments and sysobjects to query a view

5> CREATE TABLE Shippers (
6>      ShipperID int NOT NULL ,
7>      CompanyName nvarchar (40) NOT NULL ,
8>      Phone nvarchar (24) NULL
9> )
10> GO
1>
2>
3> INSERT Shippers VALUES(1,"Express","(503) 555-9831")
4> INSERT Shippers VALUES(2,"Package","(503) 555-3199")
5> INSERT Shippers VALUES(3,"Shipping","(503) 555-9931")
6> go
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2>    CREATE VIEW OregonShippers_vw
3>    AS
4>    SELECT   ShipperID,
5>             CompanyName,
6>             Phone
7>    FROM     Shippers
8>    WHERE Phone LIKE "(503)%"
9>    WITH CHECK OPTION
10> GO
1>
2>
3>    SELECT sc.text FROM syscomments sc
4>    JOIN sysobjects so
5>      ON sc.id = so.id
6>    WHERE so.name = "OregonShippers_vw"
7> GO
text










--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

   CREATE VIEW OregonShippers_vw
   AS
   SELECT   ShipperID,
            CompanyName,
            Phone
   FROM     Shippers
   WHERE Phone LIKE "(503)%"
   WITH CHECK OPTION










(1 rows affected)
1>
2> EXEC sp_helptext OregonShippers_vw;
3>
4> drop view OregonShippers_vw;
5> GO
Text
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------

   CREATE VIEW OregonShippers_vw

   AS

   SELECT   ShipperID,

            CompanyName,

            Phone

   FROM     Shippers

   WHERE Phone LIKE "(503)%"

   WITH CHECK OPTION

1>
2> drop table Shippers;
3> GO
1>
2>


Setting Permissions on a View

3>
4> CREATE TABLE employee(
5>    id          INTEGER NOT NULL PRIMARY KEY,
6>    first_name  VARCHAR(10),
7>    last_name   VARCHAR(10),
8>    salary      DECIMAL(10,2),
9>    start_Date  DATETIME,
10>    region      VARCHAR(10),
11>    city        VARCHAR(20),
12>    managerid   INTEGER
13> );
14> GO
1> INSERT INTO employee VALUES (1, "Jason" ,  "Martin", 5890,"2005-03-22","North","Vancouver",3);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (2, "Alison",  "Mathews",4789,"2003-07-21","South","Utown",4);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (3, "James" ,  "Smith",  6678,"2001-12-01","North","Paris",5);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (4, "Celia" ,  "Rice",   5567,"2006-03-03","South","London",6);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (5, "Robert",  "Black",  4467,"2004-07-02","East","Newton",7);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (6, "Linda" ,  "Green" , 6456,"2002-05-19","East","Calgary",8);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (7, "David" ,  "Larry",  5345,"2008-03-18","West","New York",9);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (8, "James" ,  "Cat",    4234,"2007-07-17","West","Regina",9);
2> GO
(1 rows affected)
1> INSERT INTO employee VALUES (9, "Joan"  ,  "Act",    6123,"2001-04-16","North","Toronto",10);
2> GO
(1 rows affected)
1>
2> select * from employee;
3> GO
id          first_name last_name  salary       start_Date              region     city                 managerid
----------- ---------- ---------- ------------ ----------------------- ---------- -------------------- -----------
          1 Jason      Martin          5890.00 2005-03-22 00:00:00.000 North      Vancouver                      3
          2 Alison     Mathews         4789.00 2003-07-21 00:00:00.000 South      Utown                          4
          3 James      Smith           6678.00 2001-12-01 00:00:00.000 North      Paris                          5
          4 Celia      Rice            5567.00 2006-03-03 00:00:00.000 South      London                         6
          5 Robert     Black           4467.00 2004-07-02 00:00:00.000 East       Newton                         7
          6 Linda      Green           6456.00 2002-05-19 00:00:00.000 East       Calgary                        8
          7 David      Larry           5345.00 2008-03-18 00:00:00.000 West       New York                       9
          8 James      Cat             4234.00 2007-07-17 00:00:00.000 West       Regina                         9
          9 Joan       Act             6123.00 2001-04-16 00:00:00.000 North      Toronto                       10
(9 rows affected)
1>
2>
3>
4> IF EXISTS (SELECT TABLE_NAME
5>    FROM   INFORMATION_SCHEMA.VIEWS
6>    WHERE  TABLE_NAME = "vEmployee")
7>    DROP VIEW vEmployee
8> GO
1> CREATE VIEW vEmployee WITH SCHEMABINDING
2> AS
3>    SELECT Id, first_name FROM dbo.Employee
4> GO
1>
2>
3> GRANT ALL
4>    ON vEmployee
5>    TO Developers
6> GO
1>
2> drop view vEmployee
3> drop table employee;
4> GO


View creation syntax

CREATE VIEW <view name>
AS
<SELECT statement>
The above syntax just represents the minimum, of course, but it"s still all we need in a large percentage of the situations. The more extended syntax looks like this:
CREATE VIEW <view name> [(<column name list>)]
[WITH [ENCRYPTION] [,SCHEMABINDING] [, VIEW_METADATA]]
AS
<SELECT statement>
WITH CHECK OPTION


VIEWS ARE STORED named SELECT statements.

Views are not a copy of your data.
Views have the look and feel of a table.
You can, with certain limitations, issue all DML statements against a view.
When you issue a query against a view, it is internally merged with the underlying 
SELECT statement and then issued against the base table or tables.


View with check option

5> CREATE TABLE Shippers (
6>      ShipperID int NOT NULL ,
7>      CompanyName nvarchar (40) NOT NULL ,
8>      Phone nvarchar (24) NULL
9> )
10> GO
1>
2>
3> INSERT Shippers VALUES(1,"Express","(503) 555-9831")
4> INSERT Shippers VALUES(2,"Package","(503) 555-3199")
5> INSERT Shippers VALUES(3,"Shipping","(503) 555-9931")
6> go
(1 rows affected)
(1 rows affected)
(1 rows affected)
1>
2>    CREATE VIEW OregonShippers_vw
3>    AS
4>    SELECT   ShipperID,
5>             CompanyName,
6>             Phone
7>    FROM     Shippers
8>    WHERE Phone LIKE "(503)%"
9>    WITH CHECK OPTION
10> GO
1>
2>
3>
4>    UPDATE OregonShippers_vw
5>    SET Phone = "(333) 555 9831"
6>    WHERE ShipperID = 1
7> GO
Msg 550, Level 16, State 1, Server J\SQLEXPRESS, Line 4
The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did
not qualify under the CHECK OPTION constraint.
The statement has been terminated.
1> drop view OregonShippers_vw;
2> GO
1>
2> drop table Shippers;
3> GO