monacemta bazebis martvis sistemebi

Size: px
Start display at page:

Download "monacemta bazebis martvis sistemebi"

Transcription

1 saqartvelos teqnikuri universiteti b. mefarisvili monacemta bazebis martvis sistemebi Tbilisi 2008

2 uak saxelmzrvanelo gankutvnilia `idmas~ specialobis meotxe kursis studentebisatvis saleqcio, praqtikuli da laboratoriuli mecadineobebisatvis, agretve magistrantebisatvis, kerzod individualuri davalebis mixedvit aplikaciis SemuSavebisaTvis SQL Server 2000-is gamoyenebit. recenzenti asoc. profesori o. gabedava sagamomcemlo saxli `teqnikuri universiteti~, 2009 ISBN yvela ufleba daculia. Aam wignis arc erti nawili (iqneba es teqsti, foto, ilustracia Tu sxva) aranairi formit da sasualebit (iqneba es eleqtronuli Tu meqanikuri), ar SeiZleba gamoyenebul iqnas gamomcemlis werilobiti nebartvis garese. saavtoro uflebebis darrveva isjeba kanonit. 2

3 Sinaarsi SQL Server - is mimoxilva... 4 Transact SQL...12 monacemta bazebis Seqmna...24 monacemta mtlianobis uzrunvelyofa...40 monacemta amorceva...52 informaciis import/eqsporti...82 kursorebis Seqmna da gamoyeneba...90 momxmareblis mier gansazrvruli funqciebi (mgf)...93 Sesanaxi procedurebi trigerebis martva warmodgenebi indeqsebi da gasarebebi tranzakciebi da blokirebebi SQL Sever - is administrireba replikacia literatura

4 SQL Server - is mimoxilva monacemta bazebis martvis sistema SQL Server - warmoadgens klient/serveris tipis mbms-s. nax. 1 a) parametrebi SQL Server -s SeuZlia gansazrvros mde mb, xolo TiToeulSi SeiZleba 2 miliardamde cxrilis gansazrvra. TiToeul cxrilsi SeiZleba 1024-mde svetis gansazrvra. ert motxovnasi SeiZleba gaertiandes 32-mde cxrilis svetebi. striqonebis raodenobaze SezRudva ar aris. yoveli cxrilisatvis ganisazrvreba 250-mde indeqsi, romeltagan mxolod erti ki, rogorc klasteruli indeqsi (clustered index). motxovnebis ena aris Transact - SQL. klient-kompiuterze da server-kompiuterze unda gamoiyenebodes erti da igive protokoli. mb-s klientis programuli uzrunvelyofa Sedgeba sxvadasxva donisagan: - daproeqtebis instrumentebi (Visual Basic, Visual C + +); - komponentebi: Distributed Transaction Coordinator - ganawilebuli tranzakciebis koordinatori; SQL Server Agent - mravalserveriani ostati; 4

5 SQL Mail - Setyobinebis mireba-gagzavna; Logins - momxmareblis saxeli-parolis gansazrvra; Server Roles - aertianebs momxmareblebs; Remote Servers - dasorebuli serveri; Linked Servers - dakavsirebuli serveri; Databases - monacemta baza; SQL Server Logs - tranzakciebis Jurnali; Data Transformation Paclogos - monacemta gadacemis paketebi; BackUp Devices - rezervirebis mowyobiloba; Web Assistant Jobs - HTML - is ostati; Database Maintenance Plans - mb-s eqsploataciis dagegmva; 5

6 nax. 2 b) danartebi grafikuli interfeisit (utilitebi) I) SQL Server Query Analizer 1. MS SQLServer - is gasveba; 2. Start/Query Analizer; Connection To SQL Server fanjarasi Segvaqvs identifikatori da paroli; 3. Microsoft SQL Server Query Analyzer fanjarasi, Database siasi vircevt mb-s; 6

7 4. Query fanjarasi Segvyavs motxovna Ctrl + E an Query / Execute Query 5. vnaxot motxovnis Sedegebi; II) Client Network Utility - gansazrvravs bibliotekebs Network Library da DB - Library; III) Server Network Utility - gansazrvravs bibliotekebs Network Library serveris mxares; IV) SQL Server BBBooks Online - eleqtronuli wignebi SQL Server - is; V) SQL Server Service Manager - aaqtiurebs, acerebs an pauzis mdgomareobasi gadahyavs procesebi; VI)SQL Server Profiler - serveris musaobis analizisatvis gamoyeneba; VII) SQL Server Enterprise Manager - axorcielebs serveris yvela administrirebas; DTC - ganawilebuli tranzakciebis koordinatori. garda amisa gamoiyeneba sxva utilitebic: DAC - gamoiyeneba statistikuri monacemebis Sesagroveblad; BCP - gamoiyeneba monacemebis mb-si Sesatanad da iqidan didi informaciis blokebis gamosatanad; Console - emsaxureba Setyobinebis Tvalyuris devnebas; Dtsrun - gamoiyeneba paketebtan, romlebic emsaxurebian monacemta gadacemas, musaobisas; Osql - gamoiyeneba Transact - SQL operatorebis, sistemur procedurebis da aseve SQL skriptebis Setana-gamotanisa da SesrulebisaTvis; iyenebs ODBC-s. Nsqlprep - gamoiyeneba programebis momzadebisatvis; Textcopy - gamoiyeneba didi teqsturi an orobiti informaciis masivebis gadasawerad. g) mb-s arqiteqtura mb- fizikuri realizacia warmoadgens or an met fails diskze. SQL Server - Si aris sistemuri mb-ebi: master, model, tempdb, msdb, agretve momxmareblis mb-ebi. 7

8 nax. 3 yvela klienturi danartebi urtiertqmedeben SQL Server- Tan erti an ori sakutari API (Application Program Interface) gamoyenebit: - ODBC (mb-s Ria SeerTeba); - DB Library (mb-s biblioteka). orive iyenebs qseluri bibliotekis (New Library) erti da igive klientur dones.sql Server ukavsirdeba klients Open Data Services danartis mesveobit, romelic irebs motxovnebs da ubrunebs Sedegebs. nax. 4 lokaluri (araqseluri) SeerTeba SeiZleba warmoiqmnas saxelobiti arxebis (named pipes) safuzvelze. qseluri biblioteka iyenebs procesebis urtiertqmedebis ertian meqanizms IPC (interprocess communication) msgavsad saxelobiti arxisa Remote procedure call (RPC) an sockets Windows. saxelobiti arxebis mxardawera xdeba protokolebit NetBEUI, Microsoft PCT / IP da NWLink. 8

9 d) kodis Tormeti wesi: 1. informaciis wesi: mb-si yvela informacia logikur doneze unda iyos warmodgenili cxrilebis saxit; 2. garantirebuli mimartva: mimartva uzrunvelyofili unda iyos cxrilis, pirveladi gasarebit da svetis saxelit; 3. aranamdvili mnisvnelobebis mxardawera; 4. dinamiuri katalogis wesi: mb-s arwera logikur doneze isetive saxis unda iyos rogorc ZiriTadSi; 5. amomwurav monacemta qveenis wesi: relaciur sistemas SeuZlia mxari dauwiros gansxvavebul enebs da momxmarebeltan urtiertobis rejims; 6. warmodgenis (virtualuri cxrilis) ganaxlebis wesi: yvela warmodgena, romelic Teoriulad SeiZleba ganaxldes unda iyos misawvdomi ganaxlebisatvis; 7. damateba, ganaxleba da amogdeba; 8. fizikur monacemta damoukidebloba: danartuli programebi da utilitebi unda iyos ucvleli fizikur doneze nebismieri cvlilebebisas monacemta Senaxvis dros; 9. logikur monacemta damoukidebloba: danartuli programebi da utilitebi unda iyos ucvleli logikur doneze nebismieri cvlilebebisas mb-s cxrilebsi; 10. mtlianobis pirobis damoukidebloba; 11. gavrcelebis damoukidebloba; 12. ertadertobis wesi. e) SQL Server - is dayeneba 1. Start / Run 2. klaviaturidan vkrifot X: \ Setup, sadac X aris CD-ROM - is Sesabamisi simbolo; 3. Welcome fanjridan iwyeba instalacia; 4. Setup Type fanjarasi vircevt: Typical, Minimum, Custom; 5. Character Set / Sort or code Collation fanjarasi ganvsazrvravt: 9

10 simboloebis krebuls (Character Set), sortirebis rigi (Sort Order) da Unicode kodirebasi sortirebis rigi (Unicode Collation); Next; 6. Network Libraries fanjarasi vayenebt qselur bibliotekebs. usityvod ketdeba (Names Pipes), TCP / IP da Multi - Protokol mxardawera; Next; 7. File Copy in Progress fanjarasi Cans distributivis serveridan failebis kopirebis procesi. v) SQL Server - is komponentebis mimoxilva SQL Server - is dayenebis martvisatvis gamoiyeneba Semdegi danartebi grafikuli interfeisit: utilita SQL Server Query Analyzer, romelic Transact - SQL instruqciebis Setanisa da Sesrulebis sasualebas izleva. misi gamoyenebisatvis sawiroa: 1. gavusvat SQL Server Service Manager, fanjarasi SQL Server Service Manager, siidan vircevt serveris saxels, servisis saxelsa da vawert Start / Continue Rilaks; 2. Start meniudan vircevt Query Analyzer komponents. Connect to SQL Server fanjarasi sawiroa identifikatorisa da parolis Setana. momxmareblis daregistrirebis Semdeg SesaZlebeli gaxdeba Query Analyzer - Tan mimartva; 3. Database siasi vircevt monacemta bazas; 4. Query teqstur velsi Segvaqvs motxovna. Semdeg vawert <Ctrl> + <E> Rilakebs an meniudan vircevt Query / Execute Query an vawert Sesabamis Rilaks instrumentebis panelze. ganvixilot Sedegebis warmodgenis awyobis zogierti parametri. Query /Set Options brzanebit ixsneba Query Options fanjara, romelsac aqvs ori CanarTi Execution da Format. konfiguraciis parametrebis awyobisatvis: File / Configure gaixsneba fanjara. General da Connection CanarTebiT. dialoguri fanjris Editor Properties gamozaxeba SesaZlebelia View / Font brzanebit. 10

11 utilita Client Network Utility, romlis dialoguri fanjara Cndeba Start meniudan, klientis danartis instrumentebis dayenebis sasualebas izleva. utilita Zalian sasargebloa, radgan klients SeuZlia ramdenime servertan SeerTeba. utilita Server Network Utility. Cndeba dialoguri fanjara Network Library Configuration, romlis mesveobitac serveris mxares dgeba kavsiri klientsa da servers Soris. danarti SQL Server Books Online warmoadgens eleqtronul dokumentacias SQL Server - is Sesaxeb. utilita SQL Server Service Manager martavs SQL Server - is procesebs, ristvisac gamoiyeneba Rilakebi: Start / Continue - gasveba; Pause - pauza; Stop - SeCereba. utilita SQL Server Profiler - gamoiyeneba serveris musaobis analizisatvis. utilita SQL Server Enterprise Manager - gamoiyeneba TiTqmis yvela administraciuli operaciis Sesrule-bisaTvis. General CanarTi Seicavs serveris Sesaxeb zogad cnobebs. CanarTze Memory aisaxeba SQL Server - is mexsi-erebastan musaobis rejimebi. Processor CanarTi SQL Server mravlprocesorian kompiuterebze musaobis sasualebas izleva. Parallelism parametrta jgufi motxovnata parale-luri SesrulebisaTvis gamoiyeneba. Security CanarTi gamoiyeneba momxmareblis SQL Server - Tan mimartvis rejimebis dayenebisatvis. Connections CanarTis danisnulebaa administra-torebis mier samomxmareblo miertebis momsaxurebis awyoba. ganawilebuli tranzakciebis koordinatori Distributed Transaction Coordinator anawilebs tranzak-ciebs serverebs Soris, rac ganawilebuli danartebisa da monacemta bazebis integraciis realizaciis sasualebas izleva. z) serveris gasvebis xerxebi 11

12 SQL Server - is aqtivizaciisatvis sistemas gaacnia ramdenime opcia. a) SQL Server Service Manager - dan: 1. Click nisanze SQL Server Service Manager; 2. Click Rilakze Start / Continue. SQL Server Service Manager dialogur fanjarasi Cndeba Running Setyobineba; 3. Click Rilakze Stop; b) SQL Server Enterprise Manager - dan: 1. gavusvat SQL Server Enterprise Manager; 2. vircevt servers da vircevt Action / Start brzanebas; serveri gasvebulia. SQL Server - is aqtivacia SeiZleba agretve danartidan an brzanebiti striqonidan: sqlserver / d drive :\directory \ DATA \ master.dat T) SeerTebis ardgena musaobis processi serveridan uecari gatisvis SemTxvevaSi, Cndeba dialoguri fanjara SeerTebis ardgenis winadadebit. 12

13 Transact SQL komentarebi: 1) /* (komentaris dasawyisi) da */ (komentaris dasasruli) 2) - - (komentaris teqsti) literalebi: mzimeebi gamoiyeneba - siis wevrebis gamosayofad; kvadratuli frcxilebi - velis saxelis misacemad; wertili- cxrilisa da velis saxelis gamosayofad; apostrofebi; varskvlavi; kitxvis nisani; Zaxilis nisani. identifikatorebi: mb-s obieqtebis identifikatorebi Sei Zleba Seicavdneb 128-mde simbolos. pirveli simbolo unda iyos aso, an #. Semdegi SeiZleba aso, cifri, an $ an ~-~. Tu simboloti masin migvititebs lokalur cvladze; simboloti masin migvititebs globalur cvladze; Tu iwyeba # simboloti masin migvititebs droebit cxrilze an proceduraze. probeli (carieli adgili) akrzalulia! gamosaxulebebi: gasareburi sityvebi: DQL ( Data QueryLanguage) - motxovnebis ena: (Select,...); DML ( Data Manipulation Language) - monacemta damusavebis ena: (Insert, Delete,...); TPL ( Transaction Processing Language) - tranzakciebis damusavebis ena: (Begin Transaction, Commit, RollBack); DDL ( Data Definition Language) - monacemta gansazrvris ena: CCL ( Cursor Control Language) - kursoris martvis ena: (Update Where current...); DCL ( Data Control Language) - monacemta martvis ena: (Grant, Revoke,...) operatorebi: aritmetikuli +, -, *, /, % Sedarebis <, > =, =, > =, >, < > Serwymis (konkatenaciis) ( + ) logikuri & (AND), (OR), ~ (NOT), ^ (XOR) monacemta tipebi: numeric - ricxviti; int an integer - ikavebs 4 baits; Smallint - ikavebs 2 baits; Tinyint - ikavebs 1 baits; real - namdvili ricxvia da ikavebs 4 baits; float [(n)] - Tu n mocemuli ar aris ikavebs 4 baits; decimal [(p[,s])] da numeric [(p[,s])] 13

14 Character - simboluri Char(n) - TiTi simbolosatvis 1 baiti; varchar(n) - cvladi sigrzis striqoni; text - didi moculobis teqsturi informaciis; nchar(n), nvarchar(n) da ntext - iyeneben unicode kodirebas; datetime : datetime, smalldatetime droisa da TariRis tipi; bit - bulis tipis monacemi; Character binary(n) - (bit patterns) varbinary(n) - bulis tipis monacemi image - didi raodenobis simboluri an orobiti informaciis; money, Smallmoney - fuladi tipis; Sysname - igivea, rac varchar(n), magram ar usvebs Null mnisvnelobas; uniqueidentifier - GUID (Globally Unique Identification) - gamoiyeneba cxrilis striqonis unikalurobis uzrunvelyofisatvis. momxmareblis mier monacemta tipis gansazrvra: 1. gavxsnat mb-s xe, SevirCioT mb; 2. User Defined Datatypes saqaraldesi avirciot New Rilaki; 3. Name velsi Segvaqvs monacemis tipis saxeli; 4. Datatype velsi vircevt ertert sistemur tips, Length velsi Segvaqvs misi sigrze; 5. Ok. funqciebi: agregaciuli: AVG sasualo aritmetikulis gamotvlis funqcia; SUM - jamis gamotvlis funqcia; MIN minimumis povnis funqcia; MAX - maqsimumis povnis funqcia; COUNT - CanawerTa datvlis funqcia. gasareburi sityva DISTINCT funqciasi COUNT operatori CUBE operatori ROLLUP striqonuli: ASCII CHAR SOUNDEX DIFFERENCE LOWER UPPER LTRIM RTRIM CHARINDEX PATINDEX 14

15 REPLICATE REVERSE RIGHT SPACE STUFF SUBSTRING STR (+) A aritmetikuli: ACOS ASIN ATAN ATAN2 COS COT SIN TAN DEGREES RADIANS CEILING FLOOR EXP LOG LOG10 PI POWER ABS RAND ROUND SIGN SQRT Text da Image: SETTEXTSIZE TEXTPTR READTEXT TEXTVALID gardaqmnis: CONVERT STR TariRis: DATENAME DATEPART GETDATE DATEADD 15

16 DATEDIFF wiladuri: USER CURRENT_USER SESSION_USER SYSTEM_USER CURRENT_TIMESTAMP APP_NAME sistemuri: asruleben operaciebs da abruneben cnobebs SQL Server -is mnisvnelobebis, obieqtebisa da awyobis Sesaxeb. ganvixilot Transact-SQL enebi: Transact-SQL enebi Data definition language (DDL) iyenebs Semdeg wesebs : CREATE object_name ALTER object_name DROP object_name CREATE DATABASE qmnis monacemta bazas. USE master CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) CREATE TABLE qmnis cxrils. 16

17 CREATE TABLE Importers ( CompanyID int NOT NULL, CompanyName varchar(40) NOT NULL, Contact varchar(40) NOT NULL ) ALTER TABLE gamoiyeneba cxrilsi cvlilebebis Sesatanad. ALTER TABLE Importers ADD ContactTitle varchar(20) NULL DROP TABLE gamoiyeneba cxrilis wasaslelad. DROP TABLE Importers Data Manipulation Language (DML) iyenebs select, insert, update da delete brzanebebs. SELECT gamoiyeneba monacemta amorcevisatvis. SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE (CustomerID = 'alfki' OR CustomerID = 'anatr') ORDER BY ContactName INSERT gamoiyeneba monacemta SetanisaTvis.. INSERT INTO Territories VALUES (98101, 'Seattle', 2) UPDATE gamoiyeneba monacemta modifikaciisatvis.. UPDATE Territories SET TerritoryDescription = 'Downtown Seattle' WHERE TerritoryID = DELETE gamoiyeneba monacemta waslisatvis. DELETE FROM Territories WHERE TerritoryID =

18 Data Control Language (DCL) aris monacemta bazaze nebartvebis martvis ena. GRANT operatori GRANT usafrtxoebis sistemasi qmnis Canawers, romelic momxmarebels mimdinare monacemta bazasi Senaxul informaciastan musaobis sasualebas azlevs. magalitad, Semdegi operatori Northwind monacemta bazasi Customers cxrilisatvis rols Public aniwebs SELECT mimartvis uflebas: GRANT SELECT ON Customers TO PUBLIC REVOKE operatori REVOKE mimdinare monacemta bazisatvis auqmebs momxmareblisatvis adre miniwebul an akrzalul nebartvebs. zemot ganxiluli magalitisatvis iqneba: REVOKE SELECT ON Customers TO PUBLIC DENY operatori DENY usafrtxoebis sistemasi qmnis elements, romelic ukrzalavs saarricxvo Canawers mimdinare monacemta bazasi Senaxul informaciastan mimartvis uflebas. DENY SELECT ON Customers TO PUBLIC 18

19 laboratoriuli samusao #1 Transact-SQL Data definition language (DDL) CREATE DATABASE : USE master CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) CREATE TABLE : CREATE TABLE Importers ( CompanyID int NOT NULL, CompanyName varchar(40) NOT NULL, Contact varchar(40) NOT NULL ) ALTER TABLE :. ALTER TABLE Importers ADD ContactTitle varchar(20) NULL DROP TABLE : DROP TABLE Importers Data Manipulation Language (DML) 19

20 SELECT : SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE (CustomerID = 'alfki' OR CustomerID = 'anatr') ORDER BY ContactName INSERT : INSERT INTO Territories VALUES (98101, 'Seattle', 2) The UPDATE statement changes data in a table. UPDATE Territories SET TerritoryDescription = 'Downtown Seattle' WHERE TerritoryID = DELETE : DELETE FROM Territories WHERE TerritoryID = GRANT : GRANT SELECT ON Customers TO PUBLIC REVOKE : REVOKE SELECT ON Customers TO PUBLIC DENY : DENY SELECT ON Customers TO PUBLIC Data Control Language (DCL) 20

21 damatebiti magalitebi: A. PRIMARY KEY is dayeneba: pubs monacemta bazis jobs cxrilis job_id velze job_id smallint PRIMARY KEY CLUSTERED am magalitsi employee cxrilis emp_id velze: emp_id empid CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED B. FOREIGN KEY is dayeneba: job_id smallint NOT NULL DEFAULT 1 REFERENCES jobs(job_id) sxvagvarad FOREIGN KEY (job_id) REFERENCES jobs(job_id) mravali velis SemTxvevaSi CONSTRAINT FK_sales_backorder FOREIGN KEY (stor_id, ord_num, title_id) REFERENCES sales (stor_id, ord_num, title_id) C. UNIQUE is dayeneba: pseudonym varchar(30) NULL UNIQUE NONCLUSTERED mravali velis SemTxvevaSi CONSTRAINT U_store UNIQUE NONCLUSTERED (stor_name, city) D. DEFAULT gansazrvrebebi jobs cxrilis job_desc velze DEFAULT 'New Position - title not formalized yet' employee cxrilisatvis DEFAULT ('9952') 21

22 /* By default the Parent Company Publisher is the company to whom each employee reports. */ DEFAULT SeiZleba Seicavdes funqcias: DEFAULT (getdate()) E. CHECK : mocemul magalitsi jobs cxrilis min_lvl da max_lvl velebis mnisvnelobebisatvis: CHECK (min_lvl >= 10) and CHECK (max_lvl <= 250) Semdeg magalitsi employee cxrilis emp_id velis mnisvnelobebisatvis: CONSTRAINT CK_emp_id CHECK (emp_id LIKE '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' OR emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]') am magalitsi publishers cxrilis pub_id velis mnisvnelobebisatvis: CHECK (pub_id IN ('1389', '0736', '0877', '1622', '1756') OR pub_id LIKE '99[0-9][0-9]') F. gansazrvrebebi mteli cxrilisatvis /* ************************** jobs table ************************** */ CREATE TABLE jobs ( job_id smallint IDENTITY(1,1) PRIMARY KEY CLUSTERED, job_desc varchar(50) NOT NULL DEFAULT 'New Position - title not formalized yet', min_lvl tinyint NOT NULL CHECK (min_lvl >= 10), max_lvl tinyint NOT NULL CHECK (max_lvl <= 250) ) /* ************************* employee table ************************* */ CREATE TABLE employee ( 22

23 ) emp_id empid CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED CONSTRAINT CK_emp_id CHECK (emp_id LIKE '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' or emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]'), /* Each employee ID consists of three characters that represent the employee's initials, followed by a five digit number ranging from through and then the employee's gender (M or F). A (hyphen) - is acceptable for the middle initial. */ fname varchar(20) NOT NULL, minit char(1) NULL, lname varchar(30) NOT NULL, job_id smallint NOT NULL DEFAULT 1 /* Entry job_id for new hires. */ REFERENCES jobs(job_id), job_lvl tinyint DEFAULT 10, /* Entry job_lvl for new hires. */ pub_id char(4) NOT NULL DEFAULT ('9952') REFERENCES publishers(pub_id), /* By default, the Parent Company Publisher is the company to whom each employee reports. */ hire_date datetime NOT NULL DEFAULT (getdate()) /* By default, the current system date is entered. */ /* ***************** publishers table ******************** */ CREATE TABLE publishers ( pub_id char(4) NOT NULL CONSTRAINT UPKCL_pubind PRIMARY KEY CLUSTERED CHECK (pub_id IN ('1389', '0736', '0877', '1622', '1756') OR pub_id LIKE '99[0-9][0-9]'), pub_name varchar(40) NULL, city varchar(20) NULL, state char(2) NULL, country varchar(30) NULL DEFAULT('USA') ) G. uniqueidentifier monacemta tipis gamoyeneba CREATE TABLE Globally_Unique_Data (guid uniqueidentifier CONSTRAINT Guid_Default 23

24 DEFAULT NEWID(), Employee_Name varchar(60), CONSTRAINT Guid_PK PRIMARY KEY (Guid) ) H. gamotvliti velisatvis gamosaxulebis gamoyeneba CREATE TABLE mytable ( low int, high int, myavg AS (low + high)/2 ) I. gamotvliti velisatvis USER_NAME funqciis gamoyeneba CREATE TABLE mylogintable ( date_in datetime, user_id int, myuser_name AS USER_NAME() ) J. NOT FOR REPLICATION gamoyeneba CREATE TABLE Sales (SaleID INT IDENTITY(100000,1) NOT FOR REPLICATION, CHECK NOT FOR REPLICATION (SaleID <= ), SalesRegion CHAR(2), CONSTRAINT ID_PK PRIMARY KEY (SaleID) ) 24

25 monacemta bazebis Seqmna SQL Server-Si monacemta bazebis Seqmnis metodebi SQL Server monacemta bazebis SeqmnisaTvis gamoiyeneba sxvadasxva metodi : SQL Server Enterprise Manager -Si console -is xe; Transact-SQL-Si CREATE DATABASE brzaneba; Create Database wizard SQL Server Enterprise Manager -is mesveobit. musaoba SQL Enterprise Manager-Si: a) monacemta bazisa da tranzakciebis Jurnalis Seqmna 1. vaaqtiurebt SQL Enterprise Manager; 2.gavxsnaT Database saqaralde; Click, menius Action / New Database brzanebaze (an marjvena nawilsi Right Click); gaixsneba Database Properties fanjara; 3. General CanarTSi Name velsi Segvaqvs monacemta bazis saxeli; Location siasi avtomaturad aisaxeba monacemta bazis failis saxeli da gza, misi zoma da jgufuri kutvnileba. am parametrebis cvlilebis SemTxvevaSi, Click Rilakze sami wertilit. gaixsneba Locate Database File fanjara, sadac vircevt monacemta bazis dislokaciis adgils, gzas, zomas da jgufur kutvnilebas. sawiroebisamebr, File Properties siasi vircevt parametrebs: Automaticaly grow file da Maximum File Size. 4. Transaction Log CanarTSi (tranzakciebis Jurnali), ukve moicema tranzakciebis failis saxeli da gza; 5. Options CanarTSi SesaZlebelia Sesaqmneli monacemta bazis sawyisi parametrebis dayeneba. monacemta bazis Tvisebebis Secvla SeiZleba opciebis mesveobit. 6. Permissions (nebartvebi) CanarTSi vircevt anu vayenebt drosebs iset obieqtebze, rogoricaa: Create Table - Create View - Create SP - 25

26 Create Default - Create Rule - Backup DB - Backup Log - monacemta bazis Seqmna SeiZleba Transact SQL - is brzanebebis sasualebitac. monacemta bazis wasla: 1. Right Click monacemta bazaze; 2. konteqstur meniusi vircevt Delete brzanebas; 3. vawert Yes Rilaks. musaoba cxrilebtan a) cxrilebis Seqmna: 1. gavxsnat monacemta bazis xe. gavaaqtiurot Table. meniusi vircevt: Action / New Table an Right Click monacemta bazaze. konteqstur meniusi: New / Table an xeze gavaaqtiurot monacemta baza. meniusi vircevt: Action / New / Table. 2. Choose Name dialogur fanjarasi: vircevt cxrilis saxels da vawert Ok Rilaks. 3. TiToeuli velisatvis Segvaqvs: Column Name - Datatype - Length - Precision - Scale - da a.s. (ix. danarti) davxurot danarti da vawert Yes Rilaks. gasveba;gasveba;gasveba; b) monacemta tipebi: (datatype) mteli ricxviti tipebi: numeric int an integer dan mde. ikavebs 4 baits. Smallint - ikavebs 2 baits (-32768, ) 26

27 tinyint - (0-255). ikavebs 1 baits. ricxviti tipebi mcocavi mzimit: (floating point): real (namdvili) ikavebs 4 baits. sizuste 7 ciframde. float [(n)] Tu n parametri mititebuli ar aris, masin ikavebs 8 baits. sizuste 15 ciframde. atobiti decimal [ ( p [, S] ) ] da ricxviti numeric [ ( P [, S ] ) ] sizuste moicema P da S argumentebit. ikavebs 2 - dan 717 baitamde. P gansazrvravs cifrta saerto raodenobas, S ki mzimis marjvniv. simboluri tipebi: char(n) TiToeuli simbolosatvis gamoiyeneba 8 baiti. n aris simboloebis maqsimaluri raodenoba. varchar(n) cvalebadi sigrzis striqonis Sesanaxad. text didi moculobis teqsturi informaciis Sesanaxad. nchar (n), nvarchar (n), ntext - gamoiyeneba Unicode - Si Sesanaxad. droiti tipebi: datetime - inaxavs TariRisa da drois 1/1/1753 dan 12/31/9999-mde. gamoiyeneba formati: MMM DD YYYY hh : mm AM / PM (usityvod); smalldatetime inaxavs TariRisa da drois 1/1/1900 dan 6/6/ mde. specialuri tipebi: bit - gamoiyeneba informaciis Sesanaxad, romelic warmodgenilia 0 an 1 - T; timestamp - gamoiyeneba mtvlelis mnisvnelobis avtomaturi damatebisatvis. binary (n) - gamoiyeneba bituri saxeebis (bit patterns) SenaxvisaTvis, Sesatani mnisvneloba unda iwyebodes simboloebit 0 x. monacemebad gamoiyenebian simboloebi 0-9 da A - F; varbinary (n) - gansxvavebit binary tipisagan varbinary SemosazRvravs velis sigrzes realuri mnisvnelobit; image - gamoiyeneba didi raodenobis simboluri an orobiti informaciis SenaxvisaTvis; money - fuladi erteulebis Sesanaxad. sizuste 0,0001 erteuli; smallmoney - igivea rac money, mxolod ufro SezRudulia; sysname - gamoiyeneba sistemuri cxrilebis svetebsi monacemebis gansazrvrisatvis. aq dausvebelia NULL mnisvneloba; 27

28 uniqueidentifier-gamoiyeneba cxrilis sqriqonis unikalurobis uzrunvelyofisatvis. g) cxrilis wasla 1. monacemta bazis xeze gavaaqtiurot Table; 2. fanjris marjvena nawilsi gavaaqtiurot sawiro cxrili; 3. Right Click. konteqstur meniusi vircevt Delete brzanebas; 4. Drop Objects fanjarasi vawert Drop All Rilaks. d) cxrilis modifikacia 1. monacemta bazis xeze gavaaqtiurot Table; 2. fanjris marjvena nawilsi gavaaqtiurot sawiro cxrili; 3. Right Click. konteqstur meniusi vircevt Design Table brzanebas; 4. Segvaqvs cvlilebebi; 5. vxuravt fanjaras. vawert Yes Rilaks. e) pirveladi gasarebis Seqmna 1. monacemta bazis xeze gavaaqtiurot Table; 2. fanjris marjvena nawilsi gavaaqtiurot sawiro cxrili; 3. Right Click. konteqstur meniusi vircevt Design Table brzanebas; 4. movnisnot veli. Right Click. konteqstur meniusi vircevt Set Primary Key. ramdenime pirveladi gasarebis SemTxvevaSi: 4. Ctrl + velebis rigrigobit monisvna. Right Click. konteqstur meniusi vircevt Properties brzanebas; 5. Properties fanjarasi, Indexes / Keys CanarTSi, Column Key velsi gavxsnat sia da SevirCioT sxva velic. vawert Close Rilakze. 3) monacemta bazis diagramebi 1. gavxsnat monacemta bazis xe; 2. Right Click monacemta bazaze. konteqstur meniusi vircevt: New / atabase Diagram Diagram Wizard dialogur fanjarasi vawert Next Rilaks; 4. Available tables velidan Add RilakiT cxrilebi gadagvaqvs diagramebis velsi. vawert Next Rilaks; 28

29 5. vawert Rilakebs Finish da Ok; 6. movnisnot erti cxrilis pirveladi gasareburi veli gadavasrialot meore cxrilis gare gasarebur velze da avusvat TiTi Tagvis Rilaks. 7. yvela kavsirebis Seqmnis Semdeg vawert Ok Rilaks. diagramasi cvlilebebis Setana 1. Right Click diagramis piktogramaze; 2. konteqstur meniusi vircevt Design Diagram; 3. Segvaqvs cvlilebebi. vxuravt fanjaras da vawert Ok Rilaks. z) monacemebis Setana cxrilsi 1. movnisnot cxrili. Right Click; 2. konteqstur meniusi vircevt: Open Table / Return all rows an Open Table / Return Top; 3. Data in Table... fanjarasi Segvaqvs monacemebi. musaoba SQL Query Analyzer -Si: CREATE DATABASE brzaneba. 1. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 2. Tu Object Browser gaxsnilia, davxurot igi. 3. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE master CREATE DATABASE BookShopDB 4. redaqtoris fanjarasi pirdapir kodis qves SevitanoT Transact-SQL Semdegi kodi : ON PRIMARY ( NAME = Bookshop_dat, 29

30 FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL\Data\Bookshop.mdf', ) SIZE = 4, MAXSIZE = 10, FILEGROWTH = 1 5. pirdapir kodis qves SevitanoT Semdegi kodi: LOG ON ( NAME = bookshop_log, FILENAME = ' C:\Program Files\Microsoft SQL Server\MSSQL\Data\Bookshop.ldf', ) SIZE = 2, MAXSIZE = 5, FILEGROWTH = 1 6. SevasruloT mteli kodi. 7. davtovot gaxsnili SQL Query Analyzer. DROP DATABASE brzaneba 1. gavaaqtiurot SQL Query Analyzer. 2. redaqtoris fanjarasi SevitanoT da SevasruloT Semdegi kodi : DROP DATABASE bookshopdb 3. davxurot SQL Query Analyzer. CREATE TABLE brzaneba 30

31 CREATE TABLE brzanebis gamoyenebis dros unda ganisazrvros, rogorc minimumi, cxrilis, svetebis saxeli da monacemta tipebi. magalitad: CREATE TABLE Customers ( CustID char(4), CustName varchar(40) ) cxrilebis martva cxrilebis Sesaxeb informaciis naxvisatvis SQL Server iyenebs ramdenime metods: sistemuri stored procedure sp_help an SQL Server Enterprise Manager. sistemuri stored procedure sp_depends an SQL Server Enterprise Manager-Si opcia Display Dependencies. svetebis Tvisebebis naxvisatvis brzaneba COLUMNPROPERTY. cxrilebis modifikacia cxrilsi SeiZleba ganxorcieldes Semdegi cvlilebebi : svetis damateba, cvlileba an wasla. PRIMARY KEY an FOREIGN KEY-is damateba an wasla. qvemot moyvanilia cxrilebis modifikaciis metodebi: Type of Modification Renaming a table Modification Methods The sp_rename system stored procedure The Rename option in SQL Server Enterprise Manager Changing the owner of a The sp_changeobjectowner system stored procedure table 31

32 Type of Modification Modifying column properties Renaming a column Modification Methods ALTER DATABASE statement The Design Table option in SQL Server Enterprise Manager The sp_rename system stored procedure The Design Table option in SQL Server Enterprise Manager cxrilebis wasla cxrilebis waslisatvis gamoiyeneba brzaneba DROP TABLE table. magalitebi: BookShopDB monacemta bazasi cxrilis Authors Semna 1. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 2. avkrifot kodi: USE bookshopdb CREATE TABLE Authors ( AuthorID SMALLINT IDENTITY(101,1) NOT NULL, FirstName VARCHAR(30) NOT NULL DEFAULT 'unknown', LastName VARCHAR(30) NOT NULL, YearBorn CHAR(4) NOT NULL DEFAULT ' N/A ', YearDied CHAR(4) NOT NULL DEFAULT ' N/A ', Description VARCHAR(200) NOT NULL DEFAULT 'N/A' ) 3. gavusvat kodi Sesrulebaze. 4. gavxsnat SQL Server Enterprise Manager da console xeze BookShopDB. 32

33 5. Click cxrilebis CanarTze. 6. Right-click cxrilze Authors da click Properties-ze. 7. properties-is naxva. BookShopDB monacemta bazasi BookAuthors da BookCondition cxrilebis Seqmna 1. avkrifot kodi : USE bookshopdb CREATE TABLE BookAuthors ( AuthorID SMALLINT NOT NULL, TitleID CHAR(8) NOT NULL ) CREATE TABLE BookCondition ( ConditionID TINYINT NOT NULL, ConditionName CHAR(10) NOT NULL, Description VARCHAR(50) NOT NULL DEFAULT 'N/A' ) 2. davbrundet SQL Server Enterprise Manager-Si. 3. Click toolbar-is Rilakze Refresh. 4. gavxsnat properties yoveli cxrilisa da view-s awyobisatvis. 5. properties-is daxurva mati naxvis Semdeg. monacemta Setana (an damateba) cxrilsi: cxrilsi (an warmodgenasi) erti an ramdenime Canaweris SetanisaTvis gamoiyeneba brzaneba INSERT Semdegi saxit: INSERT [INTO] table _or_view [(column_list)] data_values 33

34 magalitad: USE Pubs INSERT INTO NewBooks (BookTitle, PubCity) VALUES ('Life Without Fear', 'Chicago') 34

35 laboratoriuli samusao #2 monacemta bazis Seqmna ENTERPRISE MANAGER -Si 1. vaaqtiurebt SQL Enterprise Manager; 2.gavxsnaT Database saqaralde; Click, menius Action / New Database brzanebaze (an marjvena nawilsi Right Click); gaixsneba Database Properties fanjara; 3. General CanarTSi Name velsi Segvaqvs monacemta bazis saxeli; Location siasi avtomaturad aisaxeba monacemta bazis failis saxeli da gza, misi zoma da jgufuri kutvnileba. am parametrebis cvlilebis SemTxvevaSi, Click Rilakze sami wertilit. gaixsneba Locate Database File fanjara, sadac vircevt monacemta bazis dislokaciis adgils, gzas, zomas da jgufur kutvnilebas. sawiroebisamebr, File Properties siasi vircevt parametrebs: Automaticaly grow file da Maximum File Size. 4. Transaction Log CanarTSi (tranzakciebis Jurnali), ukve moicema tranzakciebis failis saxeli da gza; 5. Options CanarTSi SesaZlebelia Sesaqmneli monacemta bazis sawyisi parametrebis dayeneba. monacemta bazis Tvisebebis Secvla SeiZleba opciebis mesveobit. 6. Permissions (nebartvebi) arceva. sintaqsisi: monacemta bazis Seqmna QUERY ANALIZER -Si CREATE DATABASE database_name [ ON [ < filespec > [,...n ] ] [, < filegroup > [,...n ] ] ] [ LOG ON { < filespec > [,...n ] } ] [ COLLATE collation_name ] [ FOR LOAD FOR ATTACH ] < filespec > ::= 35

36 [ PRIMARY ] ( [ NAME = logical_file_name, ] FILENAME = 'os_file_name' [, SIZE = size ] [, MAXSIZE = { max_size UNLIMITED } ] [, FILEGROWTH = growth_increment ] ) [,...n ] < filegroup > ::= FILEGROUP filegroup_name < filespec > [,...n ] magalitebi: A. USE master CREATE DATABASE Sales ON ( NAME = Sales_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\saledat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) B. USE master CREATE DATABASE Archive ON PRIMARY ( NAME = Arch1, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat1.mdf', SIZE = 100MB, MAXSIZE = 200, FILEGROWTH = 20), ( NAME = Arch2, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat2.ndf', SIZE = 100MB, 36

37 MAXSIZE = 200, FILEGROWTH = 20), ( NAME = Arch3, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat3.ndf', SIZE = 100MB, MAXSIZE = 200, FILEGROWTH = 20) LOG ON ( NAME = Archlog1, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archlog1.ldf', SIZE = 100MB, MAXSIZE = 200, FILEGROWTH = 20), ( NAME = Archlog2, FILENAME = 'c:\program files\microsoft sql server\mssql\data\archlog2.ldf', SIZE = 100MB, MAXSIZE = 200, FILEGROWTH = 20) C. USE master CREATE DATABASE Products ON ( NAME = prods_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\prods.mdf', SIZE = 4, MAXSIZE = 10, FILEGROWTH = 1 ) D. CREATE DATABASE mytest E. USE master CREATE DATABASE Products2 ON ( NAME = prods2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\prods2.mdf' ) F. CREATE DATABASE Sales ON PRIMARY ( NAME = SPri1_dat, 37

38 FILENAME = 'c:\program files\microsoft sql server\mssql\data\spri1dat.mdf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 15% ), ( NAME = SPri2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\spri2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 15% ), FILEGROUP SalesGroup1 ( NAME = SGrp1Fi1_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\sg1fi1dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), ( NAME = SGrp1Fi2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\sg1fi2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), FILEGROUP SalesGroup2 ( NAME = SGrp2Fi1_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\sg2fi1dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ), ( NAME = SGrp2Fi2_dat, FILENAME = 'c:\program files\microsoft sql server\mssql\data\sg2fi2dt.ndf', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'c:\program files\microsoft sql server\mssql\data\salelog.ldf', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) G. B magalitis Sesabamisad SeiZleba Seiqmnas Semdegi Archive failebi: c:\program files\microsoft sql server\mssql\data\archdat1.mdf c:\program files\microsoft sql server\mssql\data\archdat2.ndf c:\program files\microsoft sql server\mssql\data\archdat3.ndf c:\program files\microsoft sql server\mssql\data\archlog1.ldf c:\program files\microsoft sql server\mssql\data\archlog2.ldf 38

39 monacemta baza SeiZleba Caixsnas sp_detach_db Sesanaxiproceduris gamoyenebit da Semdeg kvlav CREATE DATABASE is gamoyenebit FOR ATTACH Tan ertad: sp_detach_db Archive CREATE DATABASE Archive ON PRIMARY (FILENAME = 'c:\program files\microsoft sql server\mssql\data\archdat1.mdf') FOR ATTACH H. USE master CREATE DATABAS E Employees ON ( NAME = Empl_dat, FILENAME = 'f:', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'g:', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) I. USE master CREATE DATABASE Employees ON ( NAME = Empl_dat, FILENAME = 'd:\sample data dir\', SIZE = 10, MAXSIZE = 50, FILEGROWTH = 5 ) LOG ON ( NAME = 'Sales_log', FILENAME = 'd:\sample log dir\', SIZE = 5MB, MAXSIZE = 25MB, FILEGROWTH = 5MB ) 39

40 cxrilis Seqmna QUERY ANALIZER -Si sintaqsisi: CREATE TABLE [ database_name.[ owner ]. owner. ] table_name ( { < column_definition > column_name AS computed_column_expression < table_constraint > ::= [ CONSTRAINT constraint_name ] } ) [ { PRIMARY KEY UNIQUE } [,...n ] [ ON { filegroup DEFAULT } ] [ TEXTIMAGE_ON { filegroup DEFAULT } ] < column_definition > ::= { column_name data_type } [ COLLATE < collation_name > ] [ [ DEFAULT constant_expression ] [ IDENTITY [ ( seed, increment ) [ NOT FOR REPLICATION ] ] ] ] [ ROWGUIDCOL] [ < column_constraint > ] [...n ] < column_constraint > ::= [ CONSTRAINT constraint_name ] { [ NULL NOT NULL ] [ { PRIMARY KEY UNIQUE } [ CLUSTERED NONCLUSTERED ] [ WITH FILLFACTOR = fillfactor ] [ON {filegroup DEFAULT} ] ] ] [ [ FOREIGN KEY ] REFERENCES ref_table [ ( ref_column ) ] [ ON DELETE { CASCADE NO ACTION } ] [ ON UPDATE { CASCADE NO ACTION } ] [ NOT FOR REPLICATION ] ] CHECK [ NOT FOR REPLICATION ] ( logical_expression ) } < table_constraint > ::= [ CONSTRAINT constraint_nam e ] { [ { PRIMARY KEY UNIQUE } [ CLUSTERED NONCLUSTERED ] { ( column [ ASC DESC ] [,...n ] ) } [ WITH FILLFACTOR = fillfactor ] [ ON { filegroup DEFAULT } ] 40

41 ] FOREIGN KEY [ ( column [,...n ] ) ] REFERENCES ref_table [ ( ref_column [,...n ] ) ] [ ON DELETE { CASCADE NO ACTION } ] [ ON UPDATE { CASCADE NO ACTION } ] [ NOT FOR REPLICATION ] CHECK [ NOT FOR REPLICATION ] ( search_conditions ) } Northwind monacemta bazasi 1. redaqtoris panelze CREATE TABLE brzaneba: CREATE TABLE Investors ( InvestorID INT NOT NULL, FirstName varchar(30) NOT NULL, LastName varchar(30) NOT NULL ) 2. Click instrumentebis striqonze Query is Sesrulebis Rilakze. 3. Object Browser fanjarasi Cndeba Northwind da misi cxrilebi. 4. marjvena-click dbo.investors ze da Semdeg click Open -ze. 5. davxurot Open Table fanjara. cxrilis modificireba 1. redaqtoris panelze kursori davayenot Sesabamis poziciasi. 2. SevitanoT ALTER TABLE brzaneba: ALTER TABLE Investors ADD InvestmentCode INT NULL 41

42 3. gamovyot ALTER TABLE da Semdeg Click instrumentebis striqonze Query is Sesrulebis Rilakze. 4. Object Browser fanjarasi, marjvena-click dbo.investors ze da Semdeg click Open -ze. 5. davxurot Open Table fanjara. cxrilis Sesaxeb informaciis gamotana 1. redaqtoris panelze SevitanoT ALTER TABLE brzaneba: EXEC sp_help Investors 2. gamovyot EXEC brzaneba da SevasruloT. 3. gamova cxrilis Sesaxeb informacia. 4. davxurot Object Window fanjara da davtovot Query fanjara Semdegi procedurisatvis. 42

43 monacemta mtlianobis uzrunvelyofa cxrilis Employee Tvisebebis dadgena 1. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 2. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE Pubs sp_help Employee 3. gavusvat kodi Sesrulebaze. 4. cxrilis Tvisebebi (monacemta tipebi, DEFAULT gansazrvrebebi, indeqsebi, SezRudvebi da sxv.) aisaxeba ekranze. 5. davxurot SQL Query Analyzer. SezRudvebis mtlianobis Setana CREATE TABLE FactoryProcess ( EventType INT, EventTime DATETIME, EventSite CHAR(50), EventDesc CHAR(1024), CONSTRAINT event_key PRIMARY KEY (EventType, EventTime) ) PRIMARY KEY is Seqmna CREATE TABLE brzaneba svets Col1 gansazrvravs rogorc PRIMARY KEY: CREATE TABLE Table1 ( Col1 INT PRIMARY KEY, Col2 VARCHAR(30) 43

44 ) CREATE TABLE Table1 ( Col1 INT, ) ALTER TABLE Table1 Col2 VARCHAR(30), CONSTRAINT table_pk PRIMARY KEY (Col1) ADD CONSTRAINT table_pk PRIMARY KEY (Col1) FOREIGN KEY -is Seqmna CREATE TABLE brzaneba svets Col2 gansazrvravs rogorc FOREIGN KEY : CREATE TABLE Table1 ( ) CREATE TABLE Table1 Col1 INT PRIMARY KEY, Col2 INT REFERENCES Employees(EmployeeID) ( Col1 INT PRIMARY KEY, Col2 INT, ) ALTER TABLE Table1 CONSTRAINT col2_fk FOREIGN KEY (Col2) REFERENCES Employees (EmployeeID) ADD CONSTRAINT col2_fk FOREIGN KEY (Col2) REFERENCES Employees (EmployeeID) 44

45 CHECK pirobis Seqmna CHECK piroba Boolean-is gamosaxulebit abrunebs TRUE an FALSE: salary >= AND salary <= magalitad: CREATE TABLE Table1 ( Col1 INT PRIMARY KEY, Col2 INT CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000), Col3 VARCHAR(30) ) CREATE TABLE Table1 ( Col1 INT PRIMARY KEY, Col2 INT, ) ALTER TABLE Table1 Col3 VARCHAR(30), CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000) ADD CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000) Authors cxrilsi PRIMARY KEY -is damateba 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi Authors unda ganisazrvros rogorc PRIMARY KEY. 2. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 3. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE BookShopDB 45

46 ALTER TABLE Authors ADD CONSTRAINT authors_pk PRIMARY KEY (AuthorID) 4. gavusvat kodi Sesrulebaze. BookAuthors cxrilsi FOREIGN KEY damateba 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi BookAuthors unda ganisazrvros rogorc FOREIGN KEY. 2. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: ALTER TABLE BookAuthors ADD CONSTRAINT authorid_fk FOREIGN KEY (AuthorID) REFERENCES Authors (AuthorID) 3. gavusvat kodi Sesrulebaze. 4. Query is redaqtoris fanjarasi SevitanoT da Sesrulebaze gavusvat Semdegi Transact-SQL kodi: ALTER TABLE BookAuthors ADD CONSTRAINT titleid_fk FOREIGN KEY (TitleID) REFERENCES Books (TitleID) FOREIGN KEY-is damateba cxrilebsi Books, BookOrders, Orders da Employees 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilebsi Books, BookOrders, Orders, da Employees unda ganisazrvros rogorc FOREIGN KEY. 2. gamoviyenot SQL Query Analyzer cxrilebsi Books, BookOrders, Orders da Employees FOREIGN KEY-is damatebisatvis. CHECK pirobis damateba cxrilsi Customers 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi BookAuthors unda ganisazrvros rogorc CHECK piroba. 2. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: ALTER TABLE Customer 46

47 ADD CONSTRAINT checknames_ck CHECK (FirstName NOT LIKE 'unknown' OR LastName NOT LIKE 'unknown') 3. gavusvat kodi Sesrulebaze. cxrilebsi Authors da Books CHECK pirobebis damateba 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilebsi Authors da Books unda ganisazrvros rogorc CHECK piroba. 2. SevitanoT Transact-SQL kodi: USE BookShopDB ALTER TABLE Authors ADD CONSTRAINT authors1_ck CHECK (YearBorn LIKE ('[1-2][0,6-9][0-9][0-9]') OR (YearBorn = 'N/A')) ALTER TABLE Authors ADD CONSTRAINT authors2_ck CHECK (YearBorn NOT LIKE '[1][0][0-9][0-9]') ALTER TABLE Authors ADD CONSTRAINT authors3_ck CHECK (YearBorn NOT LIKE '[2][6-9][0-9][0-9]') ALTER TABLE Authors ADD CONSTRAINT authors4_ck CHECK (YearDied LIKE ('[1-2][0,6-9][0-9][0-9]') OR (YearDied = 'N/A')) ALTER TABLE Authors ADD CONSTRAINT authors5_ck CHECK (YearDied NOT LIKE '[1][0][0-9][0-9]') 47

48 ALTER TABLE Authors ADD CONSTRAINT authors6_ck CHECK (YearDied NOT LIKE '[2][6-9][0-9][0-9]') ALTER TABLE Books ADD CONSTRAINT books1_ck CHECK (PubDate LIKE ('[1-2][0,6-9][0-9][0-9]') OR (PubDate = 'N/A')) ALTER TABLE Books ADD CONSTRAINT books2_ck CHECK (PubDate NOT LIKE '[1][0][0-9][0-9]') ALTER TABLE Books ADD CONSTRAINT books3_ck CHECK (PubDate NOT LIKE '[2][6-9][0-9][0-9]') 3. gavusvat kodi Sesrulebaze. cxrilebsi Setanili pirobebis Semowmeba 1. SevitanoT da Sesrulebaze gavusvat Transact-SQL kodi: sp_helpconstraint Authors 2. gadavaxviot Grids tab vidre ar gamocndeba pirobebis seqcia. 3. SevamowmoT yvela Seqmnili pirobis arseboba. 4. davxurot SQL Query Analyzer. 48

49 cxrilis Employee Tvisebebis dadgena laboratoriuli samusao #3 monacemta mtlianobis uzrunvelyofa 3. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 4. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE Pubs sp_help Employee 4. gavusvat kodi Sesrulebaze. 6. cxrilis Tvisebebi (monacemta tipebi, DEFAULT gansazrvrebebi, indeqsebi, SezRudvebi da sxv.) aisaxeba ekranze. 7. davxurot SQL Query Analyzer. SezRudvebis mtlianobis Setana CREATE TABLE FactoryProcess ( EventType INT, EventTime DATETIME, EventSite CHAR(50), EventDesc CHAR(1024), CONSTRAINT event_key PRIMARY KEY (EventType, EventTime) ) PRIMARY KEY is Seqmna CREATE TABLE brzaneba svets Col1gansazRvravs rogorc PRIMARY KEY: CREATE TABLE Table1 ( 49

50 Col1 INT PRIMARY KEY, Col2 VARCHAR(30) ) CREATE TABLE Table1 ( Col1 INT, ) ALTER TABLE Table1 Col2 VARCHAR(30), CONSTRAINT table_pk PRIMARY KEY (Col1) ADD CONSTRAINT table_pk PRIMARY KEY (Col1) FOREIGN KEY -is Seqmna CREATE TABLE brzaneba svets Col2 gansazrvravs rogorc FOREIGN KEY : CREATE TABLE Table1 ( ) CREATE TABLE Table1 Col1 INT PRIMARY KEY, Col2 INT REFERENCES Employees(EmployeeID) ( Col1 INT PRIMARY KEY, Col2 INT, CONSTRAINT col2_fk FOREIGN KEY (Col2) REFERENCES Employees (EmployeeID) ) 50

51 ALTER TABLE Table1 ADD CONSTRAINT col2_fk FOREIGN KEY (Col2) REFERENCES Employees (EmployeeID) CHECK pirobis Seqmna CHECK piroba Boolean-is gamosaxulebit abrunebs TRUE an FALSE: salary >= AND salary <= magalitad: CREATE TABLE Table1 ( Col1 INT PRIMARY KEY, Col2 INT CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000), Col3 VARCHAR(30) ) CREATE TABLE Table1 ( Col1 INT PRIMARY KEY, Col2 INT, ) ALTER TABLE Table1 Col3 VARCHAR(30), CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000) ADD CONSTRAINT limit_amount CHECK (Col2 BETWEEN 0 AND 1000) Authors cxrilsi PRIMARY KEY -is damateba 51

52 4. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi Authors unda ganisazrvros rogorc PRIMARY KEY. 5. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 6. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE BookShopDB ALTER TABLE Authors ADD CONSTRAINT authors_pk PRIMARY KEY (AuthorID) 5. gavusvat kodi Sesrulebaze. BookAuthors cxrilsi FOREIGN KEY damateba 2. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi BookAuthors unda ganisazrvros rogorc FOREIGN KEY. 3. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: ALTER TABLE BookAuthors ADD CONSTRAINT authorid_fk FOREIGN KEY (AuthorID) REFERENCES Authors (AuthorID) 4. gavusvat kodi Sesrulebaze. 5. Query is redaqtoris fanjarasi SevitanoT da Sesrulebaze gavusvat Semdegi Transact-SQL kodi: ALTER TABLE BookAuthors ADD CONSTRAINT titleid_fk FOREIGN KEY (TitleID) REFERENCES Books (TitleID) FOREIGN KEY-is damateba cxrilebsi Books, BookOrders, Orders da Employees 3. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilebsi Books, BookOrders, Orders, da Employees unda ganisazrvros rogorc FOREIGN KEY. 4. gamoviyenot SQL Query Analyzer cxrilebsi Books, BookOrders, Orders da Employees FOREIGN KEY-is damatebisatvis. CHECK pirobis damateba cxrilsi Customers 52

53 2. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilsi BookAuthors unda ganisazrvros rogorc CHECK piroba. 3. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: ALTER TABLE Customer ADD CONSTRAINT checknames_ck CHECK (FirstName NOT LIKE 'unknown' OR LastName NOT LIKE 'unknown') 4. gavusvat kodi Sesrulebaze. cxrilebsi Authors da Books CHECK pirobebis damateba 1. gardavqmnat monacemta baza da davadginot romeli sveti (an svetebi) cxrilebsi Authors da Books unda ganisazrvros rogorc CHECK piroba. 2. SevitanoT Transact-SQL kodi: USE BookShopDB ALTER TABLE Authors ADD CONSTRAINT authors1_ck CHECK (YearBorn LIKE ('[1-2][0,6-9][0-9][0-9]') OR (YearBorn = 'N/A')) ALTER TABLE Authors ADD CONSTRAINT authors2_ck CHECK (YearBorn NOT LIKE '[1][0][0-9][0-9]') ALTER TABLE Authors ADD CONSTRAINT authors3_ck CHECK (YearBorn NOT LIKE '[2][6-9][0-9][0-9]') ALTER TABLE Authors 53

54 ADD CONSTRAINT authors4_ck CHECK (YearDied LIKE ('[1-2][0,6-9][0-9][0-9]') OR (YearDied = 'N/A')) ALTER TABLE Authors ADD CONSTRAINT authors5_ck CHECK (YearDied NOT LIKE '[1][0][0-9][0-9]') ALTER TABLE Authors ADD CONSTRAINT authors6_ck CHECK (YearDied NOT LIKE '[2][6-9][0-9][0-9]') ALTER TABLE Books ADD CONSTRAINT books1_ck CHECK (PubDate LIKE ('[1-2][0,6-9][0-9][0-9]') OR (PubDate = 'N/A')) ALTER TABLE Books ADD CONSTRAINT books2_ck CHECK (PubDate NOT LIKE '[1][0][0-9][0-9]') ALTER TABLE Books ADD CONSTRAINT books3_ck CHECK (PubDate NOT LIKE '[2][6-9][0-9][0-9]') 4. gavusvat kodi Sesrulebaze. cxrilebsi Setanili pirobebis Semowmeba 1. SevitanoT da Sesrulebaze gavusvat Transact-SQL kodi: sp_helpconstraint Authors 2. gadavaxviot Grids tab vidre ar gamocndeba pirobebis seqcia. 54

55 3. SevamowmoT yvela Seqmnili pirobis arseboba. 4.davxuroT SQL Query Analyzer. 55

56 monacemta amorceva motxovnata SeqmnisaTvis gamoiyeneba Transact - SQL - is instruqciebi, romelta Soris ert-erti gavrce-lebulia SELECT instruqcia: SELECT [ALL DISTINCT] AMamorCevis sia [INTO [axali-cxrilis-saxeli]] FROM {cxrilis-saxeli1 warmodgenis-saxeli1}[(optimizatoris-rejimi)] [[, {cxrilis-saxeli2 warmodgenis-saxeli2} [(optimizatoris-rejimi)] [...,. {cxrilis-saxeli n warmodgenis-saxeli n} [(optimizatoris rejimi)]] [WHERE winadadeba] [GROUP BY winadadeba] [HAVING winadadeba] [ORDER BY winadadeba] [COMPUTE winadadeba] [FOR BROWSE] magalitad: SELECT ProductID, ProductName, UnitPrice FROM Products WHERE UnitPrice > 40 ORDER BY UnitPrice ASC simbolo (*) arnisnavs yvela svetis saxelis yvela cxrilsi siidan cxrilebis-sia. SELECT * FROM cxrilebis-sia. cxrilidan sawiro striqonebis mocemisatvis gamoiyeneba gasareburi sityva WHERE: WHERE svetis-saxeli Sedarebis operatori mnisvneloba. Sedarebis aritmetikuli operatorebia: = tolia;! = ar aris toli; < > ar aris toli; < naklebia vidre; > metia vidre; 56

57 < = naklebia an tolia; > = metia an tolia; Like tolia mnisnelobis fragmentisa. Like operatorsi gamoiyeneba Semdegi maskebi: % - - (xazgasma) - [ ] - ^^ - OR operatoris mesveobit SeiZleba ramdenime mnisvnelobis amorceva erti svetidan. AND operatoris mesveobit motxovna sruldeba winadadebis orive pirobis Sesrulebis SemTxvevaSi. NOT operatori Caiwereba svetebis win Sedarebis operaciebsi. BETWEEN operatoris mesveobit moicema mnisvnelobata diapazoni. IN operatori zogjer ufro mosaxerxebelia vidre ramdenime operatoris gamoyeneba. NULL mnisvnelobis gamoyeneba SeiZleba, roca informacia ucnobia. NULL ar aris carieli pozicia, Cveulebrivi nuli an carieli striqoni. striqonebis sortirebuli asaxvisatvis gamoiye-neba winadadeba ORDER BY: ORDER BY svetis saxeli1,..., svetis saxeli n (DESK). DISTINCT gasareburi sityvis gamoyenebit ORDER BY winadadebasi SeiZleba aisaxos mxolod is svetebi, romlebic Sedian amorcevis siasi, anu unikaluri mnisvnelobis svetebi. garkveuli kriteriumit monacemta jgufebad gaertianebisatvis gamoiyeneba GROUP BY winadadeba: GROUP BY svetis-saxeli1,...,svetis-saxeli n. COMPUTE winadadeba gamoiyeneba funqciebtan: SUM( ), AVG( ), MIN( ), MAX( ) da COUNT( ) ertad: COMPUTE striqonta-gaertianeba(svetis-saxeli) [, striqonta-gaertianeba(svetis-saxeli,...)] [BY svetis-saxeli[, svetis-saxeli...]] winadadeba FOR BROWSE gamoiyeneba cxrilis wasakitxad, romlis SigniT mocemul momentsi sxva momxmarebeli amatebs, agdebs an anaxlebs striqons. gasareburi sityva DISTINCT gasareburi sityva DISTINCT gamoricxavs ganmeorebad striqonebs. SELECT DISTINCT ShipCity, ShipRegion 57

58 FROM Orders ORDER BY ShipCity gasareburi sityva TOP n gasareburi sityva TOP n warmoacens pirvel n striqons. SELECT DISTINCT TOP 10 ShipCity, ShipRegion FROM Orders ORDER BY ShipCity gasareburi sityva AS gasareburi sityvis AS sasualebit cxrili moicema fsevdonimis saxit table_name AS table_alias table_name table_alias magalitad: USE pubs SELECT p.pub_id, p.pub_name FROM publishers AS p informaciis tipebi Select List-Si : SELECT FirstName + ' ' + LastName AS "Employee Name", IDENTITYCOL AS "Employee ID", HomePhone, Region FROM Northwind.dbo.Employees ORDER BY LastName, FirstName ASC INTO operatori SELECT...INTO brzanebas SeuZlia ramdenime cxrilis an view-s kombinireba ert cxrilsi. 58

59 SELECT FirstName, LastName INTO EmployeeNames FROM Employers FROM operatori miutitebs romeli cxrilidan an warmodgenidan abrunebs monacemebs. SELECT * FROM Shippers operatorebi WHERE, GROUP BY da HAVING operatorebi WHERE da HAVING warmoadgenen monacemta filtrs. SELECT CustomerID, CompanyName FROM Northwind.dbo.Customers WHERE Region = 'WA' operatori HAVING gamoiyeneba mxolod GROUP BY-sTan ertad. SELECT OrdD1.OrderID AS OrderID, SUM(OrdD1.Quantity) AS "Units Sold", SUM(OrdD1.UnitPrice * OrdD1.Quantity) AS Revenue FROM [Order Details] AS OrdD1 WHERE OrdD1.OrderID in (SELECT DISTINCT OrdD2.OrderID FROM [Order Details] AS OrdD2 WHERE OrdD2.UnitPrice > $100) GROUP BY OrdD1.OrderID HAVING SUM(OrdD1.Quantity) > 100 operatori GROUP BY operatori GROUP BY ajgufebs striqonebs. 59

60 operatori ORDER BY operatori ORDER BY axdens ascending (ASC) an descending (DESC) sortirebas. USE Pubs SELECT Pub_id, Type, Title_id, Price FROM Titles ORDER BY Pub_id DESC, Type, Price magalitebi: cxrilis yvela monacemis amoreba: USE Pubs SELECT * FROM Titles cxrilis amorceviti svetebis yvela monacemis amoreba: USE Pubs SELECT Title_id, Title, Price, Ytd_sales FROM Titles cxrilis amorceviti svetebis monacemebis amoreba garkveuli pirobit: USE Pubs SELECT Title_id, Title, Price, Ytd_sales FROM Titles WHERE Price > 10 cxrilis amorceviti svetebis monacemebis mowesrigebulad amoreba garkveuli pirobit: USE Pubs SELECT Title_id, Title, Price, Ytd_sales FROM Titles WHERE Price > 10 60

61 ORDER BY Price DESC, Title monacemta gajgufeba Semajamebeli SedegiT USE Pubs SELECT Type, AVG(Price) AS AvgPrice FROM Titles WHERE Price > 10 GROUP BY Type ORDER BY AvgPrice DESC cxrilis Seqmna Semajamebeli SedegiT USE Pubs SELECT Type, AVG(Price) AS AvgPrice INTO TypeAvgPrice FROM Titles WHERE Price > 10 GROUP BY Type ORDER BY AvgPrice DESC SELECT * FROM TypeAvgPrice DROP TABLE TypeAvgPrice operatorebi Joins mravalcxriliani motxovnebis SemTxvevaSi cxrilebs Soris kavsiris dasamyareblad gamoiyeneba joins, romlis mesveobit SesaZlebelia monacemta amoreba. Joins miutitebs Tu SQL Server rogor SeuZlia gamoiyenos erti cxrilis monacemebi sxva cxrilidan monacemebis SesarCevad Inner Joins SELECT t.title, p.pub_name FROM Publishers AS p INNER JOIN Titles AS t 61

62 ON p.pub_id = t.pub_id ORDER BY Title ASC SELECT brzaneba abrunebs monacemebs Titles (t) cxrilis Title svetidan da Publishers (p) cxrilis Pub_name svetidan, sadac sruldeba p.pub_id-isa da t.pub_id is tolobis piroba.. Outer Joins ganirceva sami tipis outer joins: left, right, and full. yvela striqoni amoireba marcxena cxrilidan da mimartulia left outer join-sken, xolo marjvena cxrilis yvela striqoni amoireba marjvena cxrilidan da mimartulia right outer join-sken. full outer join-is SemTxvevaSi orive cxrilis yvela striqoni amoireba. Left Outer Joins USE Pubs SELECT a.au_fname, a.au_lname, p.pub_name FROM Authors a LEFT OUTER JOIN Publishers p ON a.city = p.city ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC Right Outer Joins USE Pubs SELECT a.au_fname, a.au_lname, p.pub_name FROM Authors a RIGHT OUTER JOIN Publishers p ON a.city = p.city ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC Full Outer Joins USE Pubs SELECT a.au_fname, a.au_lname, p.pub_name FROM Authors a FULL OUTER JOIN Publishers p 62

63 ON a.city = p.city ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC Subqueries gansazrvra SELECT brzanebis SigniT Subquery aris Casmuli SELECT, INSERT, UPDA TE, an DELETE brzanebasi (an sxvakidev subquery-si). SELECT ProductName FROM Products WHERE UnitPrice = ( SELECT UnitPrice FROM Products WHERE ProductName = 'Sir Rodney''s Scones' ) Subquery-is tipebi WHERE <expression> [NOT] IN (<subquery>) WHERE <expression> <comparison_operator> [ANY ALL] (<subquery>) WHERE [NOT] EXISTS (<subquery>) IN an NOT IN-Tan gamoyenebuli Subquery SELECT Pub_name FROM Publishers WHERE Pub_id IN ( SELECT Pub_id FROM Titles WHERE Type = 'business' 63

64 ) Comparison operatortan gamoyenebuli Subquery USE Pubs SELECT Title FROM Titles WHERE Advance > ANY ( SELECT Advance FROM Publishers INNER JOIN Titles ON Titles.Pub_id = Publishers.Pub_id AND Pub_name = 'Algodata Infosystems' ) EXISTS da NOT EXISTS gamoyenebuli Subquery USE Pubs SELECT Pub_name FROM Publishers WHERE EXISTS ( SELECT * FROM Titles WHERE Titles.Pub_id = Publishers.Pub_id AND Type = 'business' ) CUBE operatoris gamoyeneba monacemta SejamebisaTvis USE Pubs SELECT SUBSTRING(Title, 1, 65) AS Title, 64

65 SUM(qty) AS 'Quantity' FROM Sales INNER JOIN Titles ON Sales.Title_id = Titles.Title_id GROUP BY Title WITH CUBE ORDER BY Title ROLLUP operatoris gamoyeneba monacemta SejamebisaTvis magaliti 1: USE Pubs SELECT Pub_name, Au_lname, Title, SUM(qty) AS 'Sum' FROM Authors a INNER JOIN TitleAuthor ta ON a.au_id = ta.au_id INNER JOIN Titles t ON t.title_id = ta.title_id INNER JOIN Publishers p ON p.pub_id = t.pub_id INNER JOIN Sales s ON s.title_id = t.title_id GROUP BY Pub_name, Au_lname, Title WITH ROLLUP magaliti 2: SELECT ProductID, UnitPrice, SUM(Quantity) AS 'Sum' FROM [Order Details] GROUP BY ProductID, UnitPrice WITH ROLLUP ORDER BY ProductID 65

66 Inner join is gamoyeneba monacemta amorebisatvis SELECT o.customerid, o.orderid, s.companyname FROM Orders o JOIN Shippers s ON o.shipvia = s.shipperid WHERE ShipCountry = 'USA' ORDER BY o.customerid, s.companyname Left outer join is gamoyeneba monacemta amorebisatvis SELECT o.orderid, o.customerid, c.contactname, c.city FROM Orders o LEFT JOIN Customers c ON o.customerid = c.customerid AND o.shipcity = c.city ORDER BY o.orderid Right outer join is gamoyeneba monacemta amorebisatvis SELECT o.orderid, o.customerid, c.contactname, c.city FROM Orders o RIGHT JOIN Customers c ON o.customerid = c.customerid AND o.shipcity = c.city ORDER BY o.orderid Full outer join is gamoyeneba monacemta amorebisatvis 66

67 1. Use the same SELECT statement that you used in the two previous examples, except specify a full outer join. 2. Execute the Transact-SQL statement and view the Messages tab of the Results pane. 3. Click the Grids tab of the Results pane. 4. Scroll down to row 111. IN gasareburi sityva subquery -Si SELECT OrderID, EmployeeID AS EmpID FROM Orders WHERE EmployeeID IN ( SELECT EmployeeID FROM Employees WHERE City = 'Seattle' ) ORDER BY OrderID Sedarebis operatori da ALL gasareburi sityva subquery -Si SELECT OrderID, UnitPrice FROM [Order Details] WHERE UnitPrice > ALL ( SELECT UnitPrice 67

68 FROM [Order Details] JOIN Orders ON [Order Details].OrderID = Orders.OrderID AND Orders.EmployeeID = 5 ) ORDER BY UnitPrice, OrderID EXISTS gasareburi sityva subquery -Si SELECT OrderID, CustomerID FROM Orders WHERE EXISTS ( SELECT * FROM Customers WHERE Customers.CustomerID = Orders.CustomerID AND City = 'London' ) ORDER BY OrderID magalitebi: cxrilis yvela monacemis amoreba: USE Pubs SELECT * FROM Titles cxrilis amorceviti svetebis yvela monacemis amoreba: USE Pubs SELECT Title_id, Title, Price, Ytd_sales 68

69 FROM Titles cxrilis amorceviti svetebis monacemebis amoreba garkveuli pirobit: USE Pubs SELECT Title_id, Title, Price, Ytd_sales FROM Titles WHERE Price > 10 cxrilis amorceviti svetebis monacemebis mowesrigebulad amoreba garkveuli pirobit: USE Pubs SELECT Title_id, Title, Price, Ytd_sales FROM Titles WHERE Price > 10 ORDER BY Price DESC, Title monacemta gajgufeba Semajamebeli SedegiT USE Pubs SELECT Type, AVG(Price) AS AvgPrice FROM Titles WHERE Price > 10 GROUP BY Type ORDER BY AvgPrice DESC cxrilis Seqmna Semajamebeli SedegiT USE Pubs SELECT Type, AVG(Price) AS AvgPrice INTO TypeAvgPrice FROM Titles 69

70 WHERE Price > 10 GROUP BY Type ORDER BY AvgPrice DESC SELECT * FROM TypeAvgPrice DROP TABLE TypeAvgPrice 70

71 SELECT Statement: SELECT column_list FROM Table_name Using a Basic SELECT Statemen: SELECT * FROM Shippers SELECT ShipperID,CompanyName FROM Shippers laboratoriuli samusao #4 Querying Data: Using SELECT and SET to Assign Values to Variables and to Show These Values: VARCHAR(10) = 'Maria' = = @lastname Using Constants and Concatenating Strings in the Column List of SELECT: SELECT 'The name of the table is: ', table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type = 'base table' SELECT 'DROP TABLE '+ table_name FROM INFORMATION_SCHEMA.TABLES WHERE table_type = 'base table' Using String Concatenation and CAST in SELECT Statements: SELECT 'The cost per unit of '+ productname + 'is '+ CAST(unitprice as VARCHAR(10)) FROM Products Using DISTINCT to Remove Duplicate Rows from a Result Set: 71

72 SELECT title FROM Employees SELECT DISTINCT title FROM Employees Using IDENTITYCOL Instead of the IDENTITY Column Name: SELECT shipperid FROM Shippers SELECT IDENTITYCOL FROM Shippers Using Column Aliases: SELECT productname + '('+ quantityperunit + ')'as product_quantities, unitsinstock + unitsonorder units FROM Products Using the FROM Clause to Specify the Tables from Which Data Will Be Retrieved: SELEC T Territories.territorydescription, Region.regiondescription FROM Territories JOIN Region ON Territories.regionid = Region.regionid Using the FROM Clause to Specify Tables in Other Databases: SELECT au_fname + ''+ au_lname AS name FROM Pubs..Authors Using Table Aliases: SELECT T.territorydescription, R.regiondescription FROM Territories T JOIN Region R ON T.regionid = R.regionid 72

73 SELECT column_list FROM Table_name WHERE conditions Using the WHERE Clause to Restrict the Output of a Query: SELECT lastname, firstname, hiredate FROM Employees WHERE city = 'seattle' Using Operators in WHERE Clauses: SELECT lastname, firstname FROM Employees WHERE lastname LIKE 'b%' SELECT lastname, firstname, city FROM Employees WHERE city NOT IN ('seattle','redmond','tacoma') SELECT lastname, firstname, hiredate FROM Employees WHERE hiredate BETWEEN ' 'AND ' ' SELECT lastname, firstname, city FROM Employees WHERE city <> 'london'. Combining Expressions in the WHERE Clause Using AND and OR: SELECT lastname, firstname, city FROM Employees WHERE lastname LIKE 'b%' AND city NOT IN ('seattle','redmond','tacoma') SELECT lastname, firstname, city, hiredate FROM Employees WHERE hiredate BETWEEN ' 'AND ' '. OR city <> 'london' Comparing DATETIME Values in WHERE Clauses: SELECT orderid, customerid, employeeid, orderdate 73

74 FROM Orders WHERE CONVERT(VARCHAR(20),orderdate,102) = ' ' Using IS NULL and IS NOT NULL to Make Comparisons with NULL Values: SELECT companyname, contactname, region FROM Suppliers WHERE region IS NOT NULL SELECT companyname, contactname, region FROM Suppliers WHERE region IS NULL Using Optional Search Fields with Different Queries: VARCHAR(30) = NULL = 'London' IS NOT NULL IS NULL SELECT lastname, firstname, title, city FROM Employees WHERE title IS NULL IS NOT NULL SELECT lastname, firstname, title, city FROM Employees WHERE city IS NOT NULL IS NOT NULL SELECT lastname, firstname, title, city FROM Employees WHERE city AND title Using Optional Search Fields Using One Query: VARCHAR(30) = NULL = 'London' SELECT lastname, firstname, title, city FROM Employees WHERE city = ISNULL(@city,city) AND title = ISNULL(@title,title). 74

75 Data Aggregation and the GROUP BY Clause Using Aggregate Functions: SELECT AVG(unitsinstock) FROM Products SELECT COUNT(*) FROM Employees SELECT MAX(unitprice) FROM Products SELECT MIN(birthdate) FROM Employees SELECT SUM(unitsinstock) FROM Products Using DISTINCT in Aggregate Functions: SELECT COUNT(DISTINCT title) FROM Employees Using the GROUP BY Clause: SELECT title, COUNT(*) FROM Employees GROUP BY title Summarizing Data: SELECT MAX(orderdate), MIN(orderid) FROM orders Restricting the Groups Generated by GROUP BY: SELECT country, COUNT(*) 75

76 FROM Customers WHERE country IN ('Spain','Venezuela') GROUP BY country Using Column Aliases and Aggregate Functions: SELECT country, COUNT(*) AS [number of customers] FROM Customers WHERE country IN ('Spain','Venezuela') GROUP BY country Setting Restrictions on the Groups Generated by GROUP BY Using HAVING: SELECT country, COUNT(*) AS [number of customers] FROM Customers GROUP BY country HAVING COUNT(*) > 5 Combining Conditions in a HAVING Clause: SELECT country, COUNT(*) AS [number of customers] FROM Customers GROUP BY country HAVING COUNT(*) > 5 AND COUNT(*) < 10 The ORDER BY Clause Using ORDER BY to Guarantee the Order of Rows: SELECT companyname, phone FROM Shippers ORDER BY companyname Using Multiple Expressions in the ORDER BY Clause: SELECT lastname, firstname FROM Employees ORDER BY lastname ASC, firstname DESC 76

77 TOP N Clause Limiting the Output of a Query Using the TOP Clause: SELECT TOP 10 productid, productname, unitprice FROM Products ORDER BY unitprice DESC SELECT TOP 1 PERCENT product id, productname, unitprice FROM Products ORDER BY unitprice DESC Using SET ROWCOUNT: SET ROWCOUNT 10 SELECT productid, productname, unitprice FROM Products ORDER BY unitprice DESC SET ROWCOUNT 0 Using WITH TIES in TOP Clauses: SELECT TOP 6 WITH TIES productid, productname, unitsinstock FROM Products ORDER BY unitsinstock DESC Dynamically Generating and Executing Queries Using EXEC and sp_executesql: NVARCHAR(100) = 'Shippers' = N'SELECT * FROM EXEC (@query) EXEC Inserting Carriage Returns When Building Dynamic Queries : NVARCHAR(100) = N'SELECT * '+ CHAR(13)+ 'FROM Shippers' 77

78 EXEC SELECT * FROM Shippers Modifying Data: INSERT Statement: INSERT INTO Table_name (column_1,column_2,..,column_n) VALUES (value_1,value_2,..,value_n) Adding a New Row Using the INSERT Statement INSERT Territories (territoryid,territorydescription,regionid) VALUES ('77777','Fort Lauderdale',4) Omitting the Column List When Inserting Data in All Columns of the Table: INSERT Territories VALUES ('88888','Miami',4) Inserting a Row in a Table with an IDENTITY Column: INSERT Shippers (companyname, phone) VALUES ('Super Fast Shipping','(503) ') Inserting a Value in an IDENTITY Column: SET IDENTITY_INSERT Shippers ON INSERT Shippers (shipperid,companyname, phone) VALUES (20,'ACME Shipping','(503) ') SET IDENTITY_INSERT Shippers OFF Omitting Specific Columns and Using the NULL and DEFAULT Keywords: INSERT Products (productname,supplierid,categoryid,quant ityperunit, reorderlevel,discontinued) VALUES ('Donut',NULL,NULLx,'6 pieces',default,default) 78

79 INSERT Table_name DEFAULT VALUES Inserting Default Values in All Columns: INSERT Orders DEFAULT VALUES Inserting a SELECT Statement's Output into a Table: CREATE TABLE #employees_in_wa ( lastname NVARCHAR(40), firstname NVARCHAR(20) ) INSERT #employees_in_wa SELECT lastname,firstname FROM Employees WHERE region = 'WA' SELECT * FROM #employees_in_wa Inserting the Output of a Stored Procedure into a Table: CREATE PROC get_uk_employees AS SELECT lastname,firstname FROM Employees WHERE country = 'UK' CREATE TABLE #employees_in_uk ( lastname NVARCHAR(40), firstname NVARCHAR(20) ) INSERT #employees_in_uk EXEC get_uk_employees SELECT * FROM #employees_in_uk DELETE Statement: DELETE Table_name WHERE condition Deleting Rows from a Table: 79

80 DELETE Orders WHERE customerid IS NULL Using the TRUNCATE Statement to Delete All Rows from a Table: CREATE TABLE #shippers ( companyname NVARCHAR(20), phone NVARCHAR(20) ) INSERT #shippers SELECT companyname,phone FROM Shippers TRUNCATE TABLE #shippers SELECT * FROM #shippers UPDATE Statement: UPDATE Table_name SET column_1 = new_value, column_2 = new value,.. column_n = new_value WHERE condition Using the UPDATE Statement: UPDATE Shippers SET companyname = companyname + 'Express', phone = '(305) ' WHERE shipperid = 20 Storing in Variables the New Values of Columns When Updating a Single Row: SMALLINT UPDATE Products = unitsinstock = unitsinstock + 20 WHERE productname = 'Chai' SELECT INTO Statement: 80

81 Using SELECT INTO to Create and Populate Tables: SELECT lastname, firstname INTO #salesrep_employees FROM employees WHERE title = 'sales representative' SELECT * FROM #salesrep_employees Using Column Aliases with SELECT INTO: SELECT firstname + ''+ lastname AS fullname, country INTO #employeescountry FROM Employees ORDER BY fullname SELECT * FROM #employeescountry Using the IDENTITY function: SELECT IDENTITY(INT,1,1) as companyid, companyname INTO #italiancompanies FROM Customers WHERE country = 'Italy' SELECT * FROM #italiancompanies operatorebi Joins Using the ANSI SQL-89 Syntax in Inner Joins: SELECT * FROM Products, Categories WHERE Products.categoryid = Categories.categoryid Using INNER JOIN to Retrieve Information from Two Tables: SELECT productid, productname, companyname FROM Products INNER JOIN Suppliers 81

82 ON Products.supplierid = Suppliers.supplierid Using the ANSI SQL-89 Syntax in Outer Joins SELECT * FROM Territories, Region WHERE territories.regionid *= region.regionid Using the ANSI SQL-89 OUTER JOIN Syntax Along with Conditions: SELECT * FROM Territories, Region WHERE territories.regionid *= region.regionid AND region.regionid = 1 Using the ANSI SQL-92 JOIN Syntax: SELECT * FROM Products INNER JOIN Categories ON Products.categoryid = Categories.categoryid Using Restrictions Along with a JOIN Operation Using the New Syntax: SELECT * FROM Territories LEFT OUTER JOIN Region ON territories.regionid = region.regionid WHERE region.regionid = 1 Using Restrictions in the FROM Clause: SELECT * FROM Territories LEFT OUTER JOIN Region ON territories.regionid = region.regionid AND region.regio nid = 1 82

83 Performing an with Columns of Different Data Types in the JOIN Condition: CREATE TABLE Parents ( parentid INT IDENTITY(1,1) PRIMARY KEY, fullname VARCHAR(50), relationship VARCHAR(50), employeeid VARCHAR(10)) SET SHOWPLAN_TEXT ON SELECT lastname, firstname, fullname FROM employees JOIN Parents ON employees.employeeid = parents.employeeid SET SHOWPLAN_TEXT OFF DROP TABLE Parents SELECT lastname, firstname, fullname FROM employees JOIN Parents ON employees.employeeid = parents.employeeid Qualifying the Name of Columns in the Column List: SELECT Region.regionid, territorydescription, regiondescription FROM Territories JOIN Region ON Territories.regionid = Region.regionid ORDER BY Region.regionid Specifying All Columns from a Table in a Column List Using the * Keyword: SELECT Territories.* FROM Territories JOIN Region ON Territories.regionid = Region.regionid SELECT * FROM Territories JOIN Region ON Territories.regionid = Region.regionid Using Table Aliases in JOIN Operations: 83

84 SELECT P.productname, C.categoryname FROM Products P JOIN Categories C ON P.categoryid = C.categoryid Joining More Than Two Tables SELECT firstname, lastname, territorydescription, regiondescription FROM Employees E JOIN Employeeterritories ET ON E.employeeid = ET.employeeid JOIN Territories T ON ET.territoryid = T.territoryid JOIN Region R ON T.regionid = R.regionid Using JOIN in UPDATE Statements: SELECT productid, unitprice, companyname FROM Products P JOIN Suppliers S ON P.supplierid = S.supplierid WHERE companyname = 'Exotic Liquids' UPDATE Products SET unitprice = unitprice + 5 FROM Products P JOIN Suppliers S ON P.supplierid = S.supplierid WHERE companyname = 'Exotic Liquids' SELECT productid, unitprice, companyname FROM Products P JOIN Suppliers S ON P.supplierid = S.supplierid WHERE companyname = 'Exotic Liquids' Using RIGHT OUTER JOIN: INSERT Region VALUES (5,'Europe') INSERT Region VALUES (6,'Latin America') INSERT Region VALUES (7,'Asia') SELECT territoryid, territorydescription, R.regionid, regiondescription FROM Territories T RIGHT OUTER JOIN Region R ON T.regionid = R.regionid SELECT territoryid, territorydescription, R.regionid, regiondescription 84

85 FROM Territories T RIGHT OUTER JOIN Region R ON T.regionid = R.regionid WHERE territoryid IS NULL Using RIGHT JOIN to Perform a RIGHT OUTER JOIN Operation: USENorthwind SELECT territoryid, territorydescription, R.regionid, regiondescription FROM Territories T RIGHT JOIN Region R ON T.regionid = R.regionid Using LEFT OUTER JOIN: SELECT territoryid, territorydescription, R.regionid, regiondescription FROM Region R LEFT OUTER JOIN Territories T ON R.regionid = T.regionid Using FULL OUTER JOIN: SELECT S.companyname as suppliername, S.country as supcountry, C.companyname as customername, C.country as cuscountry FROM Suppliers S FULL OUTER JOIN Customers C ON S.country = C.country Using CROSS JOIN to Generate a Cartesian Product: SELECT * FROM Region SELECT categoryid, categoryname FROM Categories SELECT regionid, regiondescription, categoryid, categoryname FROM region CROSS JOIN categories Using CROSS JOIN with a JOIN Condition: USENorthwind SELECT territoryid, territorydescription, R.regionid, regiondescription 85

86 FROM Territories T CROSS JOIN Region R WHERE T.regionid = R.regionid AND R.regiondescription = 'Southern' SELECT territoryid, territorydescription, R.regionid, regiondescription FROM Territories T INNER JOIN Region R ON T.regionid = R.regionid AND R.regiondescription = 'Southern' SELECT * FROM Table1 CROSS JOIN Table2 CROSS JOIN Table3 Using a Self Join to Retrieve Hierarchy Information: SELECT E1.employeeid, E1.firstname, E1.lastname, E2.firstname as managerfirstname, E2.lastname as managerlastname FROM Employees E1 JOIN Employees E2 ON E1.reportsto = E2.employeeid WHERE E1.lastname = 'Dodsworth' AND E1.firstname = 'Anne' Using a UNION Operator with Constants in the SELECT Statements: SELECT companyname, contactname FROM Suppliers WHERE country = 'USA' UNION SELECT companyname, 'N/A'FROM Shippers Using the ALL Option in UNION Operators: SELECT city, country FROM Customers WHERE country = 'UK' UNION SELECT city, country FROM Suppliers WHERE country = 'UK' SELECT city, country FROM Customers WHERE country = 'UK' UNION ALL SELECT city, country FROM Suppliers WHERE country = 'UK' 86

87 Using an ORDER BY in a UNION Operation: SELECT city, country FROM Customers WHERE country = 'UK' UNION ALL SELECT city, country FROM Suppliers WHERE country = 'UK' ORDER BY city Creating a Table On-the-Fly with the Result of a UNION: SELECT firstname + ''+ lastname as fullname INTO #employeesandsuppliers FROM Employees UNION SELECT contactname FROM Suppliers WHERE country = 'usa' ORDER BY fullname SELECT * FROM #employeesandsuppliers 87

88 informaciis import/eqsporti ganirceva monacemta bazasi monacemta CatvirTvis Semdegi metodebi: Bulk Copy Program (BCP) programis gamoyeneba. BULK INSERT programis gamoyeneba. Data Transformation Services (DTS) sasualebis gamoyeneba. bcp utilita da BULK INSERT brzaneba bcp utilita axdens monacemta kopirebas rogorc SQL Server-Si ise misgan teqsturi failis saxit, sadac gamoiyeneba monacemta Semdegi formati. qvemot moyvanilia bcp utilitas formati aucilebeli da araaucilebeli parametrebit. bcp utilitas sintaqsisi Semdegnairia: bcp {[[monacemta_bazis_saxeli][mflobeli].]{cxrilis_saxeli warmodgenis_saxeli} "motxovna"} {in out queryout format} monacemta_faili [-m???????? _Secdomebis] [-f formatuli_faili] [-e Secdomebis_faili] [-F pirveli_striqoni] [-L ukanaskneli_striqoni] [-b jgufis_zoma] [-n] [-c] [-w] [-N] [-V ( )] [-6] [-q] [-C koduri_gverdi] [-t velebis_semzrudvei] [-r striqonebis_gamyofi] [-i Semavali_faili] [-o gamomavali_faili] [-a paketis_ zoma] [-S serveris_saxeli[\egzempliaris_saxeli ]] [-U login_id] [-P paroli] [-T] [-v] [-R] [-k] [-E] [-h "karnaxi[,...n]"] aucilebeli parametrebi parametri In (monacemta bazasi) Out (monacemta bazidan) Queryout Format cxrili masiuri kopirebis mmartveli armwerebi arwera miutitebs monacemta masiur kopirebaze monacemta bazidan cxrilsi an warmodgenasi miutitebs monacemta masiur kopirebaze cxrilidan an warmodgenidan monacemta bazasi miutitebs masiur kopirebaze monacemta bazidan miutitebs monacemta masiur kopirebaze monacemta bazidan motxovnis daxmarebit miutitebs, rom masiuri kopirebis dros BCP programa qmnis formatul fails parametrebit (-n, -c, -w, -6 an -N) da cxril/warmodgenebis SemzRudvelebiT. araaucilebeli parametrebi cxrili masiuri kopirebis araaucilebeli armwerebi 88

89 parametri arwera -a paketis_zoma miutitebs qselur paketsi baitebis raodenobaze. -b jgufis_zoma miutitebsjgufsi (paketur davalebasi) striqonebis raodenobaze. -c miutitebs, rom BCP iyenebs monacemta simbolur tips. -e SecdomaTa_faili miutitebs SecdomaTa failisadmi mimartvis gzas. -f formatuli_faili miutitebs SecdomaTa failisadmi mimartvis adre gamoyenebul gzas. -h "karnaxi[,.n]" miutitebs momxmareblisatvis karnaxebs : ORDER (sveti [ASC DESC] ). ROWS_PER_BATCH = ricxvi. KILOBYTES_PER_BATCH = ricxvi. TABLOCK. CHECK_CONSTRAINTS. -i Semavali_faili miutitebs pasuxebis failis saxels. -k miutitebs, rom carieli svetebsi Seitaneba null. -m SecdomaTa_maqsimumi miutitebs Tu BCP ramdeni Secdomis Semdeg unda Sewyvitos musaoba -n miutitebs, rom BCP iyenebs sakutari (native) tipis monacemebs -o gamomavali_faili miutitebs gamomaval failze. -q miutitebs, rom cxrilebisa da warmodgenebis saxelebisatvis sawiroa brwyalebsi Casmuli identifikatorebi. -r striqonebis_gamyofi -t velebis_semzrudveli miutitebs striqonis damtavrebis simboloze. miutitebs velebis SemzRudvelebze. -v gamoaqvs BCP programis saavtoro uflebebis Sesaxeb informacia. -w miutitebs, rom BCP iyenebs Unicode simboloebs. -C koduri_striqoni miutitebs monacemta failsi monacemta gverds. -E miutitebs, faili Seicavs mnisvnelobebs svetebis identificirebisatvis. -F pirveli_striqoni miutitebs pirvel striqonze, saidanac iwyeba masiuri kopireba. -L bolo_striqoni miutitebs bolo striqonze. -N miutitebs, rom BCP iyenebs sakutari tipis monacemebs. -P paroli miutitebs parols. -R miutitebs fulad erteuls, drosa da TariRs. -S serveris_saxeli miutitebs serveris saxels. -T miutitebs, rom gamoiyeneba ndobiti SeerTeba. -U login_id miutitebs momxmareblis login ID. -V asrulebs masiur kopirebas SQL Server-is Zveli versiis monacemta tipebis gamoyenebit. 89

90 -6 miutitebs, rom BCP iyenebs Microsoft SQL Server 6 an Microsoft SQL Server 6.5-is monacemta tipebs. rogorc zemot moyvanili cxrilebidan Cans, BCP-s gamoyenebisatvis SesaZlebelia sxvadasxva parametrebisa da agretve mati kombinaciebis gansazrvra. musaoba SQL Enterprise Manager-Si: 1. vircevt mb-s wyaros; 2. Tools / Data Transformation Services / Import into SQL an / Export from SQL; 3. vircevt mb-s monacemta mimrebs, Tu gvinda axali mb-s Seqmna Camoxsnad Database siasi vircevt New brzanebas; 4. Create Database fanjarasi ganvsazrvravt saxels, sawyis zomas da tranzakciebis Jurnals; 5. monacemta transformaciisatvis moicema ori varianti: - Copy table(s) from the source database; - Use a query to specify the data to transfer; 6. pirvel SemTxvevaSi vircevt cxrilebs, romelta monacemebi unda sxvagan SevinaxoT. Tu sawiroa yoveli cxrilis garkveuli svetebis amorceva, amisatvis vawert `...~ -s, Transform svetsi; 7. Column Mapping and Transformations fanjarasi Transformations CanarTSi vawert Advanced Rilaks; 8. Advanced Transformations Properties fanjarasi mocemulia sami varianti: - Default Transformation Flags-all possible conversions are allowed; - Require exact match between source and destination (datatype, size, precision, scale, nullability); - custom Transformation Flags; 9. Semdeg fanjarasi Segvizlia davayenot semdegi drosebi: - Run Immediately; - Create Replication Publication; - Save Package on SQL Server. am SemTxvevaSi vayenebt drosas: - Schedule DTS Package for later execution da vawert `...~-s, rata SevirCioT dro, roca es unda gaketdes; 10. Finish. musaoba SQL Query Analyzer -Si: BULK INSERT -sac gaacnia ramdenime aucilebeli da mravali araaucilebeli parametri. BULK INSERT-is sintaqsisi Semdegia: BULK INSERT [['???_????_??????'.]['????????'].] {'???_???????' '???_?????????????' FROM '????_??????' } [WITH ( [BATCHSIZE [ =??????_?????? ]] [[,] CHECK_CONSTRAINTS ] [[,] CODEPAGE [ = 'ACP' 'OEM' 'RAW' '???????_????????']] [[,] DATAFILETYPE [ = {'char' native 90

91 'widechar' widenative }]] [[,] FIELDTERMINATOR [ = '????????????_?????' ]] [[,] FIRSTROW [ =??????_?????? ]] [[,] FIRETRIGGERS [ =???????? ]] [[,] FORMATFILE [ = '????_?_??????????_?????' ]] [[,] KEEPIDENTITY ] [[,] KEEPNULLS ] [[,] KILOBYTES_PER_BATCH [ =????????_??_?????? ]] [[,] LASTROW [ =?????????_?????? ]] [[,] MAXERRORS [ =????????_?????? ]] [[,] ORDER ( {??????? [ ASC DESC ]}[,...n ])] [[,] ROWS_PER_BATCH [ =?????_??_?????? ]] [[,] ROWTERMINATOR [ = '???????????_?????' ]] [[,] TABLOCK ] )] araaucilebeli parametrebi cxrili BULK INSERT operatoris araaucilebeli parametrebi araaucilebeli parametri arwera BATCHSIZE = zoma CHECK_CONSTRAINTS CODEPAGE [ = 'ACP' 'OEM' 'RAW' 'koduri_ gverdi' ] ATAFILETYPE [ = 'char' 'native' 'widechar' 'widenative' ] miutitebs jgufsi striqonebis raodenobaze. miutitebs SezRudvaTa Semowmebaze. miutitebs monacemta failsi kodur gverdze. miutitebs monacemta failsi monacemta tipebze. FIELDTERMINATOR [ = velebis_semzrudveli ] miutitebs velebis SemzRudvelebze. FIRSTROW [ = pirveli_striqoni] FORMATFILE [ = formatuli_faili] KEEPIDENTITY KEEPNULLS KILOBYTES_PER_BATCH [ = ricxvi ] LASTROW [ = bolo_striqoni] MAXERRORS [ = SecdomaTa_maqsimumi] ORDER ( sveti [ASC DESC] ) ROWS_PER_BATCH [ = striqoni_jgufze ] pirveli striqoni kopirebisatvis. miutitebs formatul failtan mimartvis gzas. miutitebs importirebul monacemta failsi identity Tvisebis mqone svetis arsebobaze. miutitebs cariel svetebsi null mnisvnelobis arsebobaze. miutitebs jgufsi kilobaitebis raodenobaze. miutitebs masiuri kopirebis bolo striqonze. miutitebs Tu ramdeni Secdomis Semdeg unda moxdes Casma. miutitebs, Tu romel svetebsi unda moxdes monacemta sortireba. miutitebs ert jgufsi striqonebis raodenobaze. 91

92 ROWTERMINATOR [ = striqonebi_gamyofi ] miutitebs char da widechar tipis striqonebs Soris gamyofze. magalitebi: bcp brzanebis gamoyeneba BookCondition cxrilsi 1. Click Start, then click Run. 2. In the Open text box, type cmd. 3. Click OK. 4. If the command prompt is not located at the root directory, type cd c:\ and then press Enter. 5. At the C: command prompt, type bcp bookshopdb..bookcondition in bookcondition.txt -c -T, and then press Enter. BookCondition cxrilis naxva 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB SELECT * FROM BookCondition 3. Execute the Transact-SQL statement. BULK INSERT wesis gamoyeneba Positions cxrilsi 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB BULK INSERT Positions FROM 'c:\positions.txt' 92

93 WITH (DATAFILETYPE = 'CHAR') 2. Execute the Transact-SQL statement. 3. Use a SELECT statement to view the data in the Positions table. Notice that a PositionID value has been provided for each type of position. BULK INSERT wesis gamoyeneba OrderStatus da FormOfPayment cxrilebsi monacemebis importisatvis 1. Use BULK INSERT statements to insert data from the FormOfPayment.txt file to the FormOfPayment table and from the OrderStatus.txt file to the OrderStatus table. 2. Use SELECT statements to view the data within the OrderStatus table and the FormOfPayment table. BULK INSERT wesis gamoyeneba Authors table, Books table, Customers da Employees cxrilebsi monacemebis importisatvis 1. Use BULK INSERT statements to insert data from the Authors.txt file into the Authors table, from the Books.txt file into the Books table, from the Customers.txt file into the Customers table, and from the Employees.txt file into the Employees table. 2. Use SELECT statements to view the data within the four tables. bcp brzanebis gamoyeneba BookAuthors cxrilsi monacemebis importisatvis 1. Use the bcp utility to copy data from the BookAuthors.txt file into the BookAuthors table. 2. Use a SELECT statement in Query Analyzer to view the contents of the BookAuthors table. 3. Close Query Analyzer. bcp brzanebis gamoyeneba teqstur failsi monacemebis eqsportisatvis 1. At the C: command prompt, type bcp bookshopdb..books out Books2.txt -c -T, and then press Enter. 2. Use a text editor such as Notepad to view the contents of the Books2.txt file. 3. Close the Books2.txt file and the command prompt window. Data Transformation Services (DTS) 93

94 Data Transformation Services (DTS) warmoadgens SQL Server-is samsaxurebis krebuls, romlis danisnulebaa monacemta importis, eqsportis, gardaqmnisa da gadatanis organizeba. ganvixilot DTS paketis Seqmnis procesi, rodesac xdeba Northwind_Mart sacavidan monacemebis Sevseba Northwind monacemta bazasi. paketis Seqmna SesaZlebelia DTS package editor redaqtoris mesveobit, romlis gasvebisatvisac sawiroa SQL Server Enterprise Manager-is servertan mierteba, Data Transformation Services-is Meta Data Service Packages elementis povna da konteqsturi meniudan New Package opciis SerCeva. ekranze Cndeba dialoguri paneli Execute SQL Task Properties, sadac vavsebt velebs Description da SQL Statement. nax dialoguri paneli Execute SQL Task Properties Semdeg ganisazrvreba sacavis Sesavsebad sawiro monacemta nakadebi. Semdeg unda ariweros saidan ireba da gardaiqmneba monacemebi. dialoguri fanjris velsi Description vircevt opcias SQL Query da Segvaqvs SQL-moTxovnis teqsti, romlis Sedegi unda gantavsdes Time_Dim cxrilsi: SELECT DISTINCT S.ShippedDate AS TheDate, DateName(dw, S.ShippedDate) AS DayOfWeek, DatePart(mm, S.ShippedDate) AS [Month], DatePart(yy, S.ShippedDate) AS [Year], DatePart(qq, S.ShippedDate) AS [Quarter], DatePart(dy, S.ShippedDate) AS DayOfYear, 'N' AS Holiday, 94

95 case DatePart(dw, S.ShippedDate) when (1) then 'Y' when (7) then 'Y' else 'N' end AS Weekend, DateName(month, S.ShippedDate) + '_' + DateName(year,S.ShippedDate) AS YearMonth, DatePart(wk, S.ShippedDate) AS WeekOfYear FROM Orders S WHERE S.ShippedDate IS NOT NULL Click CanarTze Destination da sacavis cxrilebis siidan vircevt Time_Dim. Semdeg gadavdivart gverdze Transformations da vamowmebt Sesabamisobas monacemta sawyis krebulsa da Time_Dim cxrils Soris. Tu ar aris Sesabamisoba, mati redaqtireba SesaZlebelia New, Edit, Delete Rilakebis mesveobit. nax cxrili Time_Dim Seqmnili DTS paketi inaxeba paketebis redaqtoris menius Package Save opciis SerCeviT. SesrulebisaTvis vircevt Package Execute. monacemta sacavisa da operatiuli monacemta bazebis monacemebs Soris SesabamisobisaTvis unda Sedges ganrigi, romlis mixedvitac mocemuli paketi avtomaturad Sesruldeba. amisatvis Enterprise Manager-Si konteqsturi meniudan vircevt Schedule Package opcias. Semdeg vircevt monacemta ganaxlebis rejims Edit Recurring Job Schedule (nax. 6.3.). 95

96 nax DTS paketis Sesruleba unda arinisnos, rom paketis gasvebisatvis aucilebelia SQL Server Agent is gasveba, romelic axdens sxvadasxva davalebis Sesrulebis inicirebas. 96

97 kursorebis Seqmna da gamoyeneba kursoris (cursor) mesveobit SesaZlebelia calkeuli striqonebis damusaveba. SQL Server-Si ganirceva ori tipis kursori: klientis kursorebi (front-end an Client cursors) da serveris kursorebi (back-end an server cursors). klientis kursorebi musaoben DBLibrary - is daxmarebit, romelic axdens informaciis wakitxvas monacemta cxriluri nakadidan (Tabular Data Stream, TDS). kursorebtan dakavsirebulia xuti operacia, romelic gansazrvravs mdgomareobata Tanmimdevrobas: DECLARE, OPEN, FETCH, CLOSE, DEALLOCATE. dasawyissi aucilebelia kursoris gamocxadeba: DECLARE kursoris-saxeli [INSENSITIVE] [SCRDLL] CURSOR FOR instruqcia_select [FOR {READ ONLY UPDATE [OF svetebis-sia]}] Semdeg sawiroa kursoris gaxsna: OPEN kursoris-saxeli; kursoridan monacemta wakitxvisatvis: FETCH [[NEXT PRIOR FIRST LAST ABSOLUTE mteli-cvladi1 RELATIVE mteli-cvladi2 FROM] {[GLOBAL] kursoris-saxeli} cvladis-tipis-saxeli-kursori [ cvladis-saxeli1[,... n]] kursoris daxurva: CLOSE kursoris-saxeli atavisuflebs yvela resurss da xsnis yvela blokirebas. kursoris gatavisufleba: DEALLOCATE kursoris-saxeli gansxvavdeba daxurvisagan imit, rom mocemuli kursoris gaxsna arar moxerxdeba misi winaswari gansazrvrebis garese. kursoris Sesaxeb informaciis naxva SesaZlebelia Semdegi Sesanaxi procedurebis daxmarebit: SP_CURSOR_LIST - SP_DESCRIBE_CURSOR - SP_DESCRIBE_CURSOR_COLUMNS SP_DESCRIBE_CURSOR_TABLES - 97

98 laboratoriuli samusao #6 magalitebi: DECLARE CURSOR wesis gamoyeneba kursoris gamocxadebisatvis 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB DECLARE CustomerCrs CURSOR FOR SELECT * FROM Customers WHERE City = 'Seattle' ORDER BY LastName, FirstName 3. Execute the Transact-SQL statement. 4. In the Editor pane of the Query window, enter the following code: OPEN CustomerCrs 5. Execute the OPEN statement. FETCH wesis gamoyeneba 1. In the Editor pane of the Query window, enter the following Transact-SQL code: FETCH NEXT FROM CustomerCrs 2. Execute the Transact-SQL statement. 3. Execute the statement a second time. CLOSE wesis gamoyeneba da DEALLOCATE wesis gamoyeneba 1. In the Editor pane of the Query window, enter and execute the following Transact-SQL statement: CLOSE CustomerCrs 2. Enter and execute the following Transact-SQL statement: DEALLOCATE CustomerCrs 98

99 USE Pubs DECLARE AuthorsCursor CURSOR FOR SELECT * FROM Authors ORDER BY Au_lname SELECT wesis gamoyeneba: OPEN AuthorsCursor FETCH NEXT FROM AuthorsCursor UPDATE Authors SET Phone = ' ' WHERE CURRENT OF AuthorsCursor CLOSE AuthorsCursor DEALLOCATE AuthorsCursor DECLARE CURSOR wesis gamoyeneba: 3. Open Query Analyzer and connect to your local server. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB DECLARE CustomerCrs CURSOR FOR SELECT * FROM Customers WHERE City = 'Seattle' ORDER BY LastName, FirstName 4. Execute the Transact-SQL statement. 5. In the Editor pane of the Query window, enter the following code: OPEN CustomerCrs 6. Execute the OPEN statement. FETCH wesis gamoyeneba: 2. In the Editor pane of the Query window, enter the following Transact-SQL code: FETCH NEXT FROM CustomerCrs 3. Execute the Transact-SQL statement. 4. Execute the statement a second time. CLOSE wesis gamoyeneba da DEALLOCATE wesis gamoyeneba: 2. In the Editor pane of the Query window, enter and execute the following Transact-SQL statement: 99

100 CLOSE CustomerCrs 3. Enter and execute the following Transact-SQL statement: DEALLOCATE CustomerCrs 100

101 momxmareblis mier gansazrvruli funqciebi (mgf) User-Defined Functions samomxmareblo monacemta tipis Seqmna SesaZlebelia Enterprise Manager-is mesveobit Semdegi bijebis SesrulebiT. 1. Enterprise Manager-Si saqaraldis gverdit vawert + nisans. Sedegad ixsneba SQL Server-Ta jgufi, Semdgom serveri. vxsnit saqaraldes Databases, Semdeg monacemta bazas. 2. Click Rilakze User Defined Data Types da konteqstur meniusi vircevt New User Defined Data Type. 3. velsi Name Segvaqvs monacemta axali tipis saxeli. magalitad: brand_type. nax Semdeg vizlevit SQL Server monacemta sistemur tipsa da samomxmareblo tipis velis sigrzes. agretve, tipis Sesabamisa vayenebt drosas Allow NULLs da Default pirobebs. 4. Click Rilakze OK. samomxmareblo monacemta tipis amogdeba SesaZlebelia Semdegi bijebis SesrulebiT: 101

102 1. Enterprise Manager-Si vawert + nisans saqaraldis gverdit. Sedegad ixsneba SQL Server-Ta jgufi, Semdgom serveri. vxsnit saqaraldes Databases, Semdeg monacemta bazas. 2. Click Rilakze User Defined Data Types. marjvena panelze gamocndeba samomxmareblo monacemta tipebi. 3. Click samomxmareblo monacemta tipis Rilakze, romlis waslac gvinda. konteqstur meniusi vircevt Delete. Cndeba fanjaradrop Objects. 4. waslamde vawert Show Dependencies-ze. Cndeba dialoguri fanjara Dependencies, sadac nacvenebia monacemta bazebis obieqtebi, romlebic damokidebulni arian samomxmareblo monacemta tipebze. nax saqaralde User Defined Data Types 102

103 nax fanjara Drop Objects 5. Tu samomxmareblo monacemta tiptan dakavsirebit problemebi ar arinisneba, masin vxuravt fanjaras Dependencies, Semdeg fanjarasi Drop Objects vawert Rilaks Drop All. nax fanjara Dependencies 103

104 samomxmareblo monacemta tipebis waslis dros warmosobili Secdomebi aisaxeba SetyobinebaSi. nax Secdomebis fanjara 104

105 laboratoriuli samusao #7 magalitebi: Using Undocumented Built-In User-Defined Functions PRINT CHAR(10) + 'fn_chariswhitespace(char(9))' + CHAR(10) select fn_chariswhitespace(char(9)) PRINT CHAR(10) + 'fn_mssharedversion(1)' + CHAR(10) select master.dbo.fn_mssharedversion(1) PRINT CHAR(10) + 'fn_replgetbinary8lodword(0x )' + CHAR(10) select fn_replgetbinary8lodword(0x ) PRINT CHAR(10) + 'fn_replmakestringliteral(@a)' + CHAR(10) varchar(100) = 'peter is right' select fn_replmakestringliteral(@a) PRINT CHAR(10) + 'fn_replprepadbinary8( )' + CHAR(10) select fn_replprepadbinary8( ) PRINT CHAR(10) + 'fn_replquotename("hello")' + CHAR(10) select fn_replquotename('hello') fn_chariswhitespace(char(9)) fn_mssharedversion(1) fn_replgetbinary8lodword(0x ) fn_replmakestringliteral(@a) 105

106 N'peter is right' fn_replprepadbinary8( ) x0C BA59ABE fn_replquotename("hello") Table-Valued, Built-In, User-Defined Functions PRINT CHAR(10) + 'fn_helpcollations' + CHAR(10) select * from ::fn_helpcollations() WHERE name LIKE 'Cyrillic%' PRINT CHAR(10) + 'fn_listextendedproperty(null, NULL, NULL, NULL, NULL, NULL, NULL)' + CHAR(10) select * from ::fn_listextendedproperty(null, NULL, NULL, NULL, NULL, NULL, NULL) PRINT CHAR(10) + 'fn_msfulltext()' + CHAR(10) select * from master.dbo.fn_msfulltext() fn_helpcollations Use fn_dblog to Look at the Transaction Log PRINT CHAR(10) + 'fn_log(null, NULL)' + CHAR(10) select TOP 10 [Current LSN], Operation from ::fn_dblog(null, NULL) ORDER BY [Current LSN] DESC fn_log(null, NULL) 106

107 Creating Scalar User-Defined Functions -- Returns the maximum ProductID from Products CREATE FUNCTION dbo.maxproductid () RETURNS int AS BEGIN RETURN ( SELECT MAX(ProductID) FROM dbo.products ) END -- Returns who and from where the query is executed CREATE FUNCTION dbo.whowhere () RETURNS nvarchar(256) AS BEGIN RETURN SYSTEM_USER + 'FROM ' + APP_NAME() END -- Returns the date of the latest executed statement -- which is usually today CREATE FUNCTION dbo.today () RETURNS smalldatetime AS BEGIN smalldatetime = CONVERT(varchar(10), MAX(last_batch), 112) FROM master.dbo.sysprocesses END -- Function that produces a non-predictable -- Pseudo-Random Number CREATE FUNCTION dbo.prand () RETURNS float AS BEGIN datetime varchar(3) 107

108 float float float -- Obtain the time of latest executed statement = ( SELECT MAX(last_batch) FROM master.dbo.sysprocesses ) -- Select only the milliseconds = 114), 3) -- Scramble the digits = CAST(SUBSTRING(@dts, 2, 1) + RIGHT(@dts, 1) + LEFT(@dts, 1) AS int) -- Obtain the time of latest executed statement = ( SELECT MAX(last_batch) FROM master.dbo.sysprocesses ) -- Select only the milliseconds = 114), 3) -- Scramble the digits = CAST(SUBSTRING(@dts, 2, 1) + RIGHT(@dts, 1) + LEFT(@dts, 1) AS int) -- Select the random number = '0'+ / pi(), 2), 21), 16) -- Return the random number END New Definition for the Random Function Using Other Base Functions -- Create a base function to extract a three-digits -- number based on the scrambled version of the -- milliseconds information of the latest executed -- statement in SQL Server CREATE FUNCTION dbo.get3rand () RETURNS int AS BEGIN datetime varchar(3) = ( 108

109 SELECT MAX(last_batch) FROM master.dbo.sysprocesses ) = 114), 3) RETURN CAST(SUBSTRING(@dts, 2, 1) + RIGHT(@dts, 1) + LEFT(@dts, 1) AS int) END -- Create the new NewPRand Random function -- based on the Get3Rand function CREATE FUNCTION dbo.newprand () RETURNS float AS BEGIN float = '0'+ LEFT(RIGHT(CONVERT(varchar(40), dbo.get3rand() * dbo.get3rand() / pi(), 2), 21), 16) RETURN (@r) END Using Table Variables Inside a Scalar User-Defined Function CREATE FUNCTION dbo.mediumproductunitprice () RETURNS money AS BEGIN -- Create hosting table variable TABLE( id int identity(1,1), UnitPrice money) -- Inserts the product prices in ascending order INSERT (UnitPrice) SELECT UnitPrice FROM Products ORDER BY UnitPrice ASC -- Selects the medium price RETURN ( SELECT MAX(UnitPrice) WHERE ID <= (SELECT MAX(ID) / 2 ) 109

110 END Failing to Provide a Parameter Produces a Syntax Error -- This is an illegal call, because it does not provide -- a value for parameter SELECT dbo.totalprice (12, 25.4) -- This is a valid call, because it does provide -- a value for every parameter SELECT dbo.totalprice (12, 25.4, 0.0) You Can Apply Scalar User-Defined Functions to Table Fields -- Use the TotalPrice function to retrieve -- information from the Order Details table SELECT OrderID, ProductID, dbo.totalprice(quantity, UnitPrice, Discount) AS TotalPrice FROM [Order Details] WHERE ProductID = Use the SimpleEncrypt function to encrypt product na mes SELECT ProductID, dbo.simpleencrypt(productname) AS EncryptedName FROM Products WHERE CategoryID = 3 -- Use the SimpleDecrypt function to decrypt -- a field encrypted with the SimpleEncrypt function SELECT ProductID, dbo.simpledecrypt(encryptedname) AS ProductName FROM ( SELECT ProductID, CategoryID, dbo.simpleencrypt(productname) AS EncryptedName FROM Products ) AS P WHERE CategoryID = 3 110

111 Sesanaxi procedurebi (Stored procedure) Sesanaxi procedurebi, romelta daxmarebit iqmneba qveprogramebi, musaoben usualod serverze. SQL ena araprocedurulia, magram SQL Server - Si gamoiyeneba gasareburi sityvebi, romlebic monawileoben procedurebis Seqmnis dros da isini SeiZleba Senaxul iqnan Semdeg Sesrulebamde. nacvlad programirebis standartuli enebis (C an Visual Basic) gamoyenebisa, SQL Server - is mb-si operaciata Sesasruleblad SeiZleba Stored procedure gamoyeneba. mati SeqmnisaTvis gamoiyeneba instruqcia CREATE PROCEDURE: CREATE PROC[EDURE] proceduris-saxeli[; ricxvi] [{ parametri monacemta-tipi}[varing] [=mnisvneloba-utqmelad] [OUTPUT] ] [,... n] [WITH { RECOMPILE ENCRYPTION RECOMPILE< ENCRYPTION } ] [FOR REPLICATION] AS SQL_instruqciebi misi aqtivizaciisatvis viyenebt EXEC[UTE] brzanebas. axali proceduris Seqmna SeiZleba mxolod mimdinare mb-satvis. SQL Server Query Analyzer - is musaobisas mimdinare mb-s dayeneba sruldeba operatorit: USE mb-s saxeli, romelsic unda Seiqmnas Sesanaxi procedura. Sesanaxi proceduris Seqmna SeiZleba SQL Server Enterprise Manager - is daxmarebitac: a) Sesanaxi proceduris Seqmna: 1. SevirCioT serveri da mb; 2. Stored procedure - ze marjvena Click, konteqstur meniusi vircevt New Stored procedure; 3. fanjarasi < PROCEDURE NAME > nacvlad Segvaqvs axali proceduris saxeli, mag. all_authors; 4. Click, Check Syntax da Ok. arsebobs Sesanaxi proceduris Seqmnis meore xerxic: 1. Click, panelis Rilakze Run a Wizard; 2. Select Wizard fanjarasi gavxsnat Database da avirciot Create Stored Procedure Wizard; Next; 3. vircevt mb-s, Next; 4. vircevt obieqts da moqmedebebs, romelic proceduram unda Seasrulos, Next; 5. iqmneba procedurebi. naxvis an modifikaciisatvis Edit / SQL; 6. Finish; Ok. b) Sesanaxi proceduris wasla: 1. gavxsnat mb, Stored Procedures sia; 2. marjvena Click wasaslel proceduraze da vircevt Delete brzanebas; 111

112 3. Drop ALL. yvela Sesanaxi procedura iqyeba prefiqsit SP_ da imyofeba mb-si master. sistemuri procedurebi SP_HELPTEXT da SP_HELP gamoiyenebian mb-s iseti obieqtebis sanaxavad, rogoricaa cxrilebi, wesebi da instalaciebi usityvod. Sesanaxi procedurebis amogdeba xdeba rogorc SQL Server Query Analyzer - Si: DROP PROCEDURE proceduris-saxeli-1[,..., proceduris-saxeli-n ] aseve SQL Server Enterprise Manager - Si: 1. davayenot kursori sawiro proceduraze da marjvena Click; 2. konteqstur meniusi vircevt DELETE brzanebas. Sesanaxi procedurebis Sesrulebis martvisatvis gamoiyeneba Transact - SQL - is Semdegi konstruqciebi: konstruqcia IF... ELSE: konstruqcia BEGIN... END: instruqcia WHILE: gasareburi sityva BREAK: gasareburi sityva CONTINUE: Transact - SQL - Si lokaluri cvladebi ganisazrvreba instruqciit: cvladis-saxeli monacemta-tipi [,... n] globaluri cvladebi programasi ar ganisazrvreba, aramed sistemasi serveris doneze. instruqcia PRINT cvladebtan: gasareburi sityva TO gasareburi sityva RETURN gasareburi sityva RAISERROR instruqcia WAITFOR gamosaxuleba CASE Stored Procedure-ebis kategoriebi ganirceva stored procedure-ebis xuti klasi : sistemuri stored procedures, lokaluri stored procedures, droebiti stored procedures, gafartoebuli stored procedures da dasorebuli stored procedures. sistemuri stored procedures inaxeba sistemur monacemta bazasi Master da arinisneba sp_ prefix-it. USE Pubs EXECUTE sp_table_privileges Stores lokaluri Stored Procedures inaxeba momxmareblis monacemta bazasi. droebiti Stored Procedures arsebobs vidre SQL Server daixureba, mere ki waisleba. gafartoebuli stored procedure iyenebs 32-bit dynamic link library (DLL), SesaZleblobebis gasafartoeblad. magalitad, xp_sendmail programa, romelic agzavnis mesijebs da motxovnata Sedegebs akavsirebs recipient-ebze. magalitisatvis sp_prepare aris droebiti Stored Procedure, xolo xp_logininfo ar aris droebiti Stored Procedure: USE Master 112

113 --an extended stored procedure that uses an sp_ prefix. SELECT OBJECTPROPERTY(object_id('sp_prepare'), 'IsExtendedProc') es magaliti abrunebs 1-is mnisvnelobas. USE Master --a stored procedure that is not extended but uses an xp_ prefix SELECT OBJECTPROPERTY(object_id('xp_logininfo'), 'IsExtendedProc') es magaliti abrunebs 0-is mnisvnelobas. dasorebuli stored procedures asrulebs proceduras dasorebul SQL Server-ze ganawilebuli motxovnebis dros. Stored procedure-is Sinaarsis naxva 1. Click dbo.sp_who object-ze. 2. Right-click dbo.sp_who. 3. Click Scripting Options. 4. Click the Include Descriptive Headers In The Script check box and click OK. 5. Right-click dbo.sp_who. 6. Point to Script Object To New Window As and click Create. 7. Click New Query on the toolbar or press CTRL + N. 8. In the Editor pane of the Query window, enter the following Transact-SQL code: sp_helptext [master.dbo.sp_who] 9. Execute the code. Stored Procedure-is Seqmnis magaliti: USE Pubs CREATE PROCEDURE [dbo].[listauthornames] AS SELECT [au_fname], [au_lname] FROM [pubs].[dbo].[authors] droebiti Stored Procedure-is Seqmnis magaliti: --create a local temporary stored procedure. 113

114 CREATE PROCEDURE #localtemp AS SELECT * from [pubs].[dbo].[authors] --create a global temporary stored procedure. CREATE PROCEDURE ##globaltemp AS SELECT * from [pubs].[dbo].[authors] --create a temporary stored procedure that is local to tempdb. USE TEMPDB CREATE PROCEDURE directtemp AS SELECT * from [pubs].[dbo].[authors] Stored Procedure-is dajgufeba, kesireba da Sifracia USE Pubs CREATE PROC [dbo].[protected] WITH ENCRYPTION AS SELECT [au_fname], [au_lname] FROM [pubs].[dbo].[authors] --check if stored procedure is encrypted and if so, return 1 for IsEncrypted SELECT OBJECTPROPERTY(object_id('protected'), 'IsEncrypted') --if the stored procedure is encrypted, return "The object comments have been encrypted." EXEC sp_helptext protected parametrebisa da mati mnisvnelobebis gansazrvra --call the stored procedure with the parameter values. USE Pubs EXECUTE au_info Green, Marjorie --call the stored procedure with parameter names and values. USE Pubs EXECUTE = = 'Marjorie' Stored Procedure-is amoqmedeba, roca SQL Server iwyebs musaobas USE Master EXECUTE sp_procoption 114

115 @procname = = = true USE Master --determine whether a stored procedure is set to start automatically SELECT OBJECTPROPERTY(object_id('autostart'), 'ExecIsStartup') To disable stored procedures from starting automatically, you can run the sp_configure stored procedure. EXECUTE = 'scan for startup = 0 RECONFIGURE Stored Procedure-is modifikacia User-defined Stored Procedure-is modifikaciisatvis gamoiyeneba ALTER PROCEDURE an mokled ALTER PROC. kerzod, gadarqmevisatvis gamoiyeneba sp_rename. USE PUBS EXECUTE = = = 'object' Stored Procedure-is wasla: am SemTxvevaSi gamoiyeneba DROP PROCEDURE an mokled DROP PROC. USE pubs DROP PROCEDURE procedure01, procedure02 115

116 laboratoriuli samusao #8 magalitebi: Stored procedure-is Seqmna Northwind-Si database 1. Open Query Analyzer and connect to your local server. 2. Close the Object Browser window if it is displayed. 3. Expand the Query window so that it occupies all of the workspace in Query Analyzer. 4. In the Editor pane of the Query window, enter and execute the following code: USE northwind CREATE PROCEDURE char(5) AS SELECT ContactName, ContactTitle FROM Customers WHERE CustomerID SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName 5. Review but do not spend too much time on the SELECT statements that appear below the AS keyword. To view the stored procedure object in Query Analyzer 1. Open the Object Browser in Query Analyzer and expand the Northwind database. 2. Expand the Stored Procedures node. 3. Expand the dbo.custorderhistrep stored procedure. 4. Expand the Parameters node. 5. Expand the Dependencies node. 6. Switch to the Editor pane of the Query window. 7. On a blank line at the bottom of the Editor pane, enter and execute the following line: 116

117 sp_depends custorderhistrep 8. Do not close Query Analyzer, because you will use it in the next practice. Stored procedure-is Sesrulebaze gasveba 1. On a blank line at the bottom of the Editor pane, enter and execute the following code: EXEC = 'thecr' 2. In the previous example, EXEC was specified to run the stored procedure. Was it necessary to use this keyword? 3. Find the dbo.custorderhistrep stored procedure in the Object Browser and right-click it. 4. From the context menu, point to Script Object to New Windows As and then click Execute. 5. In the Editor pane, click the mouse at the end of the EXEC statement so that a blinking cursor appears after the Append the following line to the end of the line: = 'thecr'. The EXEC statement should look like the following: = = 'thecr' 6. Execute the query. 7. Close the new page created in the Query window, but do not close Query Analyzer or the original page that appears in the Editor pane. 8. Click No. Stored procedure-is modificireba 1. In the Editor pane of the Query window, locate the following code: CREATE PROCEDURE char(5) AS SELECT ContactName, ContactTitle FROM Customers WHERE CustomerID SELECT ProductName, Total=SUM(Quantity) FROM Products P, [Order Details] OD, Orders O, Customers C WHERE C.CustomerID AND C.CustomerID = O.CustomerID AND O.OrderID = OD.OrderID AND OD.ProductID = P.ProductID GROUP BY ProductName 117

118 2. Change the CREATE keyword to ALTER. 3. You want the order quantity to be listed in Descending order. Add the following statement below the GROUP BY ProductName statement: ORDER BY Total DESC 4. You have also decided to move the table joins from the WHERE clause to the FROM clause. The final form of the code should be similar to the following: ALTER PROCEDURE char(5) AS SELECT ContactName, ContactTitle FROM Customers WHERE CustomerID SELECT ProductName, Total=SUM(Quantity) FROM Products P INNER JOIN [Order Details] OD ON P.ProductID = OD.ProductID JOIN Orders O ON OD.OrderID = O.OrderID JOIN Customers C ON O.CustomerID = C.Custo merid WHERE C.CustomerID GROUP BY ProductName ORDER BY Total DESC 5. Execute the query. 6. To verify that the changes were made, go to the bottom of the Editor pane, press ENTER, then enter and execute the following statement: sp_helptext custorderhistrep 7. Leave the Query Analyzer open for the next exercise. Stored procedure-is wasla 1. Go to the bottom of the Editor pane, press ENTER, then enter and execute the following statement: DROP PROCEDURE dbo.custorderhistrep 2. Use the Object Browser in Query Analyzer or Enterprise Manager to verify that the stored procedure was removed. 118

119 3. Close the Query Analyzer. 4. If you wish to save this script, press Yes. Otherwise, press No. Stored Procedures-is daprogrameba Parameters and Variables. The following procedure shows the use of both input and output parameters: USE Pubs CREATE PROCEDURE varchar(80), -- This is the input int OUTPUT, -- This is the first output varchar(80) O UTPUT --This is the second output parameter. AS -- Assign the column data to the output parameters and -- check for a title that's like the title input parameter. = FROM titles WHERE title -- Declare variables to receive output values from procedure. varchar(80) EXECUTE SalesForTitle --set the values for output parameters to the = "%Garlic%" --specify a value for input parameter. -- Display the variables returned by executing the procedure. Select "Title" "Number of Sales" varchar(80) EXECUTE SalesForTitle "%Garlic%", --sets the value of the input OUTPUT, --receives the first output OUTPUT --receives the second output parameter -- Display the variables returned by executing the procedure. Select "Title" "Number of Sales" The RETURN Statement and Error Handling The following example shows how to modify the SalesForTitle stored procedure to use a RETURN code (and thus provide a more useful message): 119

120 ALTER PROCEDURE int varchar(80) OUTPUT AS --Check to see if the title is in the database. If it isn't, --exit the procedure and set the return code to 1. IF (SELECT COUNT(*) FROM titles WHERE title = 0 RETURN(1) ELSE = FROM titles WHERE title The following example sets the input equal to Garlic%: to hold the result code. int --Run the procedure and equal to the procedure. = = "Garlic%" --Determine the value and execute the code. = 0 SELECT "Title" "Number of Sales" "Return Code" ELSE = 1 PRINT 'No matching titles in the database. Return code=' + CONVERT(varchar(1),@r_Code) If you don't enter a value for input parameter, the result of executing the query is the following message: Server: Msg 201, Level 16, State 3, Procedure SalesForTitle, Line 0 Procedure 'SalesForTitle' expects parameter '@Title', which was not supplied. Default Values and Setting a Pa rameter to NULL Modifying the procedure in the following way accomplishes this goal: ALTER PROCEDURE varchar(80) = int varchar(80) OUTPUT AS IS NULL RETURN(2) ELSE IF (SELECT COUNT(*) FROM titles WHERE title = 0 RETURN(1) 120

121 ELSE = FROM titles WHERE title When you execute the procedure, you must include a test for a return code of 2, as shown in the following example: int = OUTPUT --No value specified for input parameter. = 0 SELECT "Title" "Number of Sales" "Return code" ELSE = 1 PRINT 'No matching titles in the database. Return code=' + CONVERT(varchar(1),@r_Code) ELSE = 2 --test for a return code of 2. PRINT 'You must add a value for this procedure to function properly. Return code=' + CONVERT(varchar(1),@r_Code) Testing for Server Errors SELECT error, description from master.dbo.sysmessages The following example demonstrates how to generate a return code if there is a database error: ALTER PROCEDURE varchar(80) = int varchar(80) OUTPUT AS IS NULL RETURN(2) ELSE IF (SELECT COUNT(*) FROM dbo.titles WHERE title = 0 RETURN(1) ELSE = FROM dbo.titles WHERE title -- Check for SQL Server database errors. <> 0 RETURN(3) The following code executes the procedure and displays a generic error message if a database error occurs: 121

122 int = = "%Garlic%" = 0 SELECT "Title" "Number of Sales" "Return code" ELSE = 1 PRINT 'No matching titles in the database. Return code=' + CONVERT(varchar(1),@r_Code) ELSE = 2 PRINT 'You must add a value for this procedure to function properly. Return code=' + CONVERT(varchar(1),@r_Code) ELSE = 3 PRINT 'There was a database error.' Nesting Procedures Nesting stored procedures simply involves calling one stored procedure from another. A single stored procedure can perform multiple tasks, but it is better to create simpler, more generic stored procedures that can call other stored procedures to complete additional tasks. Data Retrieval Methods use cursors in stored procedures ALTER PROCEDURE varchar(80) AS SELECT Title = title, [Number of Sales]=ytd_sales FROM titles WHERE title Notice that all output parameters were removed from the stored procedure. To execute this simple stored procedure, you can use the following sample code: EXECUTE = "The%" When you execute this procedure, the result set is as follows: Title Number of Sales The Busy Executive's Database Guide

123 Title Number of Sales The Gourmet Microwave 22,246 The Psychology of Computer Cooking NULL ALTER PROCEDURE CURSOR VARYING varchar(80) = NULL AS = CURSOR FOR SELECT ytd_sales, title FROM dbo.titles WHERE title After the SELECT statement, the OPEN statement populates the result set into the cursor. The following code can be used to execute this stored procedure: CURSOR EXECUTE = "The%" FETCH NEXT WHILE (@@FETCH_STATUS <> -1) BEGIN FETCH NEXT END To create an insert customer stored procedure 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter and execute the following code: USE BookShopDB CREATE PROCEDURE dbo.addcustomer --CustomerID not included as an input parameter because --the ID is automatically generated (Identity varchar(60) = varchar(12) AS INSERT [BookShopDB].[dbo].[Customers] (FirstName, LastName, Phone, Address1, Address2, City, State, Zip) VALUES 123

124 @Zip) RETURN(SELECT AS 'Identity') 3. In the Editor pane of the Query window, enter and execute the following code: = = = = '20 Oak St., = = = '98888' SELECT [Customer ID] = 'The new customer ID is:' + To add error-handling techniques to the stored procedure 1. In the Editor pane of the Query window, enter and execute the following code: ALTER PROCEDURE varchar(30)= varchar(30)= varchar(24) = varchar(60) = varchar(60) = varchar(15) = varchar(7) = varchar(12) = NULL AS IF (@FirstName = 'unknown') AND (@LastName = 'unknown') RETURN(1) ELSE IS NULL RETURN(2) ELSE IS NULL IS NULL IS NULL IS NULL RETURN(3) ELSE INSERT [BookShopDB].[dbo].[Customers] (FirstName, LastName, Phone, Address1, Address2, City, State, Zip) @City, AS 'Identity') <> 0 RETURN(4) 2. In the Editor pane of the Query window, enter and execute the following code: int 124

125 EXECUTE = = = '20 Oak St., = = = '98888' = 4 BEGIN PRINT 'A database error has occured. Please contact the help desk for assistance.' END = 1 PRINT 'You must specify a value for the firstname or lastname' ELSE = 2 PRINT 'You must specify a value for the phone number' ELSE = 3 PRINT 'You must provide all address information, Street address, City, State and Zipcode' ELSE SELECT [Customer ID] = 'The new customer ID is: ' + To create a stored procedure to protect against customer record duplication 1. In the Editor pane of the Query window, enter and execute the following code: CREATE PROCEDURE varchar(30)= varchar(30)= varchar(15) = varchar(7) = varchar(24) = varchar(30) varchar(30) varchar(15) varchar(7) varchar(24) OUTPUT @o_phone=phone FROM customers WHERE firstname=@1_firstname AND lastname=@1_lastname AND city=@1_city AND state=@1_state AND phone=@1_phone <> 0 RETURN(5) 2. In the Editor pane of the Query window, enter and execute the following code: ALTER PROCEDURE varchar(30)= varchar(30)= varchar(24) = varchar(60) = varchar(60) = varchar(15) = varchar(7) = varchar(12) = NULL AS 125

126 IF = 'unknown') AND = 'unknown') RETURN(1) ELSE IS NULL RETURN(2) ELSE IS NULL IS NULL IS NULL IS NULL RETURN(3) --begin nesting @o_firstname OUTPUT > 0 BEGIN PRINT 'A duplicate record was found for ' + ' ' PRINT 'in ' + ' ' + ' with a phone number ' PRINT 'of ' + '.' RETURN(5) END --end nesting INSERT [BookShopDB].[dbo].[Customers] (FirstName, LastName, Phone, Address1, Address2, City, State, Zip) @City, AS 'Identity') <> 0 RETURN(4) To test the stored procedures 1. In the Editor pane of the Query window, enter and execute the following code: = = = '20 Oak St., = = = '98888' = 4 BEGIN PRINT 'A database error has occured. 126

127 Please contact the help desk for assistance.' END = 1 PRINT 'You must specify a value for the firstname or lastname' ELSE = 2 PRINT 'You must specify a value for the phone number' ELSE = 3 PRINT 'You must provide all address information, Street address, City, State and Zipcode' ELSE SELECT [Customer ID] = 'The new customer ID is: ' + 2. Change the value to Jeff to Fellinge, then execute the query again. 127

128 trigerebis martva trigeri warmoadgens Sesanaxi procedurebis gansakutrebul tips, romelic aqtiurdeba cxrilsi monacemta cvlilebebis (UPDATE, INSERT da DELETE) mcdelobisas. trigerebi ganisazrvrebian konkretuli cxrilebisatvis. SQL Server ganixilavs trigers, ert mtlians - rogorc ert tranzakcias, romelic ar fiqsirdeba an ukan brundeba. a) trigeris Seqmna SQL Server Enterprise Manager - is daxmarebit xdeba Semdegnairad: 1. gavxsnat serveri, mb, cxrilebis sia; 2. marjvena Click sasurvel adgilze; konteqstur meniusi vircevt Task / Manager triggers; 3. fanjarasi, romelsic SeiZleba teqstis Setana: CREATE TRIGGER [trigeris-saxeli] ON cxrilis-saxeli FOR INSERT, UPDATE, DELETE (aq mietiteba moqmedeba, roca trigeri unda amusavdes) AS da vaniwebt saxels; 4. Ok. b) trigeris Sesaxeb informaciis asaxva SesaZlebelia SQL Server Enterprise Manager - is an sistemuri procedurebis SP_HELP da SP_DEPENDS gamoyenebit. ganvixilot pirveli xerxi: 1. gavusvat SQL Server Enterprise Manager; 2. vircevt servers, mb-s, cxrils; vircevt Design Table; 3. marjvena Click cxrilze, vircevt Design Table; 4. fanjarasi vawert panelis Rilaks Triggers; 5. fanjarasi Trigger Properties SesaZlebelia nebis-mieri dayenebuli trigeris teqstis baxva. aqve SeiZleba trigeris teqstsi dasasvebi cvlilebebis Setana. g) trigeris amogdeba xdeba instruqciit: DROP TRIGGER [mflobeli] trigeris-saxeli. monacemta mtlianobis dacvis miznit Access-dan mb-s konvertirebisatvis aucilebelia proceduris SP_HELP gamoyeneba. 128

129 Trigger-ebis Seqmna Transact-SQL is gamoyenebit CREATE TRIGGER brzaneba SeiZleba Camoyalibdes Semdegi saxit: CREATE TABLE trigger_name ON table_name or view_name FOR trigger_class and trigger_type(s) AS Transact-SQL statements 129

130 laboratoriuli samusao #9 Transact-SQL enis aspeqtebi Transact-SQL enis Semdegi pirobebi ar gamoiyeneba trigerebsi: ALTER, CREATE, DROP, RESTORE, and LOAD DATABASE LOAD and RESTORE LOG DISK RESIZE and DISK INIT RECONFIGURE brzaneba CREATE TRIGGER CREATE TRIGGER brzanebis ilustraciisatvis ganvixilot Semdegi magaliti: USE BookShopDB CREATE TRIGGER dbo.alerter Trigger names must follow the rules for identifiers. For example, if you decide to create a trigger named Alerter for the Employees Table, you must enclose the name in brackets as shown: CREATE TRIGGER dbo.[alerter for employees table] piroba ON: Use the ON clause to instruct the trigger on to what table or view it should be applied. CREATE TRIGGER dbo.alerter ON dbo.employees pirobebi FOR, AFTER da INSTEAD OF: CREATE TRIGGER dbo.alerter ON dbo.employees FOR INSERT, UPDATE, DELETE an kidev: CREATE TRIGGER dbo.alerter ON dbo.employees INSTEAD OF INSERT, UPDATE, DELETE Notice that the FOR clause is replaced with INSTEAD OF. 130

131 piroba AS : USE BookShopDB CREATE TRIGGER dbo.alerter ON dbo.employees AFTER INSERT, UPDATE, DELETE AS EXEC master..xp_sendmail 'BarryT', 'A record was just inserted, updated or deleted in the Employees table.' trigerebis Altering da Renaming ALTER TRIGGER dbo.alerter ON dbo.employees AFTER UPDATE AS EXEC master..xp_sendmail 'BarryT', 'A record was just updated in the Employees table.' trigerebis Viewing, Dropping, and Disabling select * from bookshopdb..sysobjects where type = 'tr' Use the sp_helptrigger system stored procedure to show the properties of a trigger = employees You can query the Text column of the SysComments system table to see the contents of the stored procedure. use the sp_helptext system stored procedure. = alerter Deleting a trigger removes it from the SysComments and SysObjects system tables. Use the DROP TRIGGER statement to delete one or more triggers from a database USE BookShopDB DROP TRIGGER [dbo].[alerter] To disable a trigger, use the ALTER TABLE statement. ALTER TABLE employees DISABLE TRIGGER alerter 131

132 martivi trigeris Seqmna Authors cxrilisatvis BookShopDB-Si 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter and execute the following code: USE BookShopDB CREATE TRIGGER dbo.insertindicator ON dbo.authors AFTER INSERT AS PRINT 'The insert trigger fired.' 3. In the Editor pane of the Query window, enter and execute the following code: CREATE TRIGGER dbo.updateindicator ON dbo.authors AFTER UPDATE AS PRINT 'The update trigger fired.' CREATE TRIGGER dbo.deleteindicator ON dbo.authors AFTER DELETE AS IF <> 0 PRINT 'The delete trigger fired.' trigeris testireba Authors cxrilisatvis 1. In the Editor pane of the Query window, enter and execute the following code: INSERT INTO authors (firstname, lastname, yearborn, yeardied) VALUES ('Max', 'Doe', 1962, 'N/A') 2. In the Editor pane of the Query window, enter and execute the following code: UPDATE authors SET authors.firstname = 'Tucker' WHERE authors.firstname = 'Max' 3. In the Editor pane of the Query window, enter and execute the following code: DELETE authors where firstname = 'Tucker' 132

133 trigeris rename, modify, and view 1. In the Editor pane of the Query window, enter the following stored procedure 2. Execute the query. 3. In the Editor pane of the Query window, enter and execute the following stored procedure code: = authors 4. In the Editor pane of the Query window, enter and execute the following code: ALTER TRIGGER dbo.insupdcontrol ON dbo.authors INSTEAD OF INSERT, UPDATE AS PRINT 'Inserts and updates are not allowed at this time.' 5. In the Editor pane of the Query window, enter and execute the following code: SET NOCOUNT ON INSERT INTO authors (firstname, lastname, yearborn, yeardied) VALUES ('Max', 'Doe', 1962, 'N/A') SET NOCOUNT OFF 6. Run a SELECT statement against the Authors table to verify that no record was added. 7. In the Editor pane of the Query window, enter and execute the following stored procedure code: The stored procedure displays the contents of the InsUpdControl trigger. trigeris disable and drop 1. In the Editor pane of the Query window, enter and execute the following code: ALTER TABLE authors DISABLE TRIGGER insupdcontrol The ALTER TABLE statement disables the InsUpdControl trigger on the Authors table. 2. In the Editor pane of the Query window, enter and execute the following code: 133

134 INSERT INTO authors (firstname, lastname, yearborn, yeardied) VALUES ('Max', 'Doe', 1962, 'N/A') SELECT * FROM Authors where Firstname = 'Max' 3. In the Editor pane of the Query window, enter and execute the following code: DROP TRIGGER insupdcontrol, updateindicator, deleteindicator DELETE authors where firstname = 'Max' Inserted and Deleted fsevdo cxrilisatvis When an INSERT, UPDATE, or DELETE trigger fires, the event creates one or more pseudo tables (also known as logical tables). CREATE TRIGGER dbo.updatetables ON dbo.authors AFTER UPDATE AS SELECT "Description" = 'The Inserted table:' SELECT * FROM inserted SELECT "Description" = 'The Deleted table:' SELECT * FROM deleted trigeris Syntax, System Commands, and Functions UPDATE (column_name ) and (COLUMNS_UPDATED()) Clauses IF UPDATE (first_name) OR UPDATE (Last_Name) BEGIN Do some conditional processing when either of these columns are updated. END 134

135 warmodgenebi (VIEW) warmodgena aris monacemta asli cxrilidan (cxrilebidan) an sxva warmodgenebidan. isini e.w. virtualur cxrilebs warmoadgenen, radgan rogorc damoukidebeli obieqti mb- Si ar arseboben. Access - Si mat motxovnebs uwodeben. warmodgenis Seqmna SeiZleba mxolod mimdinare mb-si. Transact - SQL - is sasualebit warmodgenis Seqmnis sintaqsisi Semdegia: CREATE VIEW warmodgenis-saxeli [(sveti1[, sveti2,...])] [WITH ENCRYPTION] - DdaSifvra AS SELECT instruqcia FROM cxrilis-saxeli warmodgenis-saxeli [winadadeba WHERE] [WITH CHECK OPTION] SQL Server Enterprise Manager-is daxmarebit iqneba: 1. mimdinare mb-s SigniT gamovyot saqaralde SQL Server Views; 2. konteqstur mrniusi vircevt New SQL Server View punqts; 3. New View fanjarasi SeiZleba ubralod SevitanoT instruqcia an visargeblot grafikuli interfeisit: - gadavitanot fokusi Diagram fanjarasi. vawert Add Table, Segvaqvs cxrilebi; - Grid Pane qvefanjris Column svetsi Camoxsnad siasi vircevt svets(vels); - Output svetsi vayenebt drosas, Tu Semajamebel nakrebsi ar unda aisaxos; - Criteria svetsi Segvaqvs amorcevis kriteriumi; - vawert Save (an Save As ) brzanebas da Ok. 4. vawert Run. warmodgenis gansazrvreba inaxeba sistemur cxrilsi syscoments. am informaciis asaxvisatvis gamoiyeneba procedura SP_HELPTEXT. a) warmodgenis redaqtireba warmodgenis redaqtirebisatvis SQL Server Enterprise Manager - is sasualebit sawiroa: 1. im mb-si, sadac iyo Seqmnili warmodgena (saqaraldesi Databases) vircevt SQL Server Views; 135

136 2. warmodgenaze marjvena click-it, konteqstur meniusi vircevt Design SQL Server View; 3. SevasruloT yvela sawiro cvlileba da vawert instrumentebis panelze Save brzanebas. Tu CREATE VIEW instruqciasi davamatebt WITH ENCRYPTION (anu dasifvra) winadadebas, masin warmodgenis gansazrvrebis naxva SeuZlebeli gaxdeba. cxrilebisa da warmodgenebis asaxvisatvis gamoiyeneba procedura SP_DEPENDS. SeiZleba agretve SQL Server Enterprise Manager-is daxmarebitac, ristvisac marjvena click warmodgenaze da konteqstur meniusi avirciot: Task Display Dependencies. warmodgenebis gansazrvris dros unda gavitvaliswinot Semdegi SezRudvebi: * ar SeiZleba warmodgenis gansazrvra droebiti cxrilisatvis romlebic arseboben manam, sanam xdeba monacemta wakitxva mudmivi cxrilebidan da mati asaxva. * warmodgenisatvis ar SeiZleba trigeris gansazrvra. (trigerebze qvemot gveqneba saubari). * warmodgenis gansazrvrasi ar SeiZleba CarTva winadadebebis: ORDER BY; COMPUTE; SELECT gasareburi sityvit DISTINCT; INTO. * warmodgenebsa da cxrilebs unda hqondet msgavsi an identuri maxasiateblebi. b) warmodgenidan warmodgenis Seqmna. warmodgenidan warmodgenis Seqmna SesaZlebelia SQL Server Enterprise Manager-iT. fanjarasi Dependencies for warmodgenis saxeli, sadac damokidebul obieqtta siasi, warmodgena ucvenebs mdgeneli warmodgenebisa da cxrilebis ramdenime dones. analogiuri informacia miireba proceduris SP_DEPENDS daxmarebit. warmodgenebsi SesaZlebelia sabazo cxrilebis svetebis gadarqmeva warmodgenis gansazrvrebasi: CREATE VIEW warmodgenis-saxeli [(warmodgenis-sveti1,... warmodgenis sveti n)] AS SELECT instruqcia... FROM cxrilis-saxeli an warmodgenis-saxeli [WHERE winadadeba] moicema alternatiuli svetebis saxelebis sia. SerCevis Semdeg gamoiyeneba Semdegi sintaqsisi: SELECT svetis-zveli-saxeli = svetis-axali-saxeli. g) warmodgenis gadarqmeva 136

137 saxeli; warmodgenis gadarqmevisatvis gamoiyeneba sistemu-ri procedura SP_RENAME: SP_RENAME Zveli-saxeli, axali-saxeli. igive SesaZlebelia SQL Server Enterprise Manager - is sasualebitac: 1. gamovyot warmodgena; 2. marjvena Click, konteqstur meniusi vircevt Rename brzanebas; Segvaqvs axali 3. Enter. d) mb-dan warmodgenis amogdeba mb-dan warmodgenis amogdebisatvis gamoiyeneba Transact SQL - is brzaneba: DROP VIEW warmodgenis-saxeli1,..., warmodgenis-saxeli n. an SQL Server Enterprise Manager-iT: 1. gamovyot warmodgena. marjvena Click; 2. konteqstur meniusi vircevt Delete brzanebas; 3. Drop Object fanjarasi vawert Drop All. monacemta ganaxlebisatvis: vircevt warmodgenas. marjvena Click; 2. konteqstur meniusi: Open Table Return All Rows (an Open Table / Return Top); 3. vircevt ujreds (ujredebs). Segvaqvs axali mnisvnelobebi. Tu monacemebis amogdeba gvinda, gamovyoft striqons da vawert Delete brzanebas. warmodgenebis Seqmna. musaoba SQL Query Analyzer -Si: CREATE VIEW brzanebis gamoyeneba Transact-SQL-Si: CREATE VIEW CustomerOrders AS SELECT o.orderid, c.companyname, c.contactname FROM Orders o JOIN Customers c ON o.customerid = c.customerid ganawilebuli warmodgenebis Seqmnis miznit unda Sesruldes Semdegi bijebi: 1. Add a linked server definition named Server2 with the connection information for Server2 and a linked server definition named Server3 for access to Server3. 137

138 2. Create the following distributed partitioned view: CREATE VIEW Customers AS SELECT * FROM CompanyDatabase.TableOwner.Customers_33 UNION ALL SELECT * FROM Server2.CompanyDatabase.TableOwner.Customers_66 UNION ALL SELECT * FROM Server3.CompanyDatabase.TableOwner.Customers_99 3. Perform the same steps on Server2 and Server3. warmodgenebis modifikacia ALTER VIEW CustomerOrders AS SELECT o.orderid, o.orderdate, c.companyname, c.contactname FROM Orders o JOIN Customers c ON o.customerid = c.customerid warmodgenebis wasla DROP VIEW CustomerOrders 138

139 laboratoriuli samusao #10 BookAuthorView s Seqmna BookShopDB-Si: 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB CREATE VIEW BookAuthorView AS SELECT a.firstname, a.lastname, b.title FROM Authors a JOIN BookAuthors ba ON a.authorid = ba.authorid JOIN Books b ON ba.titleid = b.titleid 3. Execute the Transact-SQL statement. 4. If the Object Browser window is not displayed, open it now. 5. In the object tree of the Object Browser window, locate the new view that you created. 6. Expand the Columns node. BookAuthorView s modifikacia BookShopDB-Si: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB ALTER VIEW BookAuthorView AS SELECT a.firstname, a.lastname, b.titleid, b.title FROM Authors a JOIN BookAuthors ba ON a.authorid = ba.authorid JOIN Books b ON ba.titleid = b.titleid 2. Execute the Transact-SQL statement. 3. In the object tree of the Object Browser window, locate the BookAuthorView view and expand the Columns node. 4. Close Query Analyzer. 139

140 BookAuthorView s wasla BookShopDB-dan: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB DROP VIEW BookAuthorView 2. Execute the Transact-SQL statement. 3. In the object tree of the Object Browser window, locate the Views node for the BookShopDB database. monacemta naxva warmodgenebis mesveobit: SELECT * FROM CustomerOrders The following SELECT statement retrieves the OrderID column and the OrderDate column for any orders made for the QUICK-Stop company: SELECT OrderID, OrderDate FROM CustomerOrders WHERE CompanyName = 'quick-stop' ORDER BY OrderID monacemta modifikacia warmodgenebis mesveobit: a) monacemta damateba: CREATE VIEW CustomerView AS SELECT CustomerID, CompanyName FROM Customers To insert data through the CustomerView view, you should use the INSERT statement (as shown in the following example): INSERT CustomerView VALUES ('TEST1', 'Test Company') 140

141 b) monacemta gacvla: UPDATE CustomerView SET CustomerID = 'TEST2' WHERE CustomerID = 'TEST1' g) monacemta wasla warmodgenebis mesveobit: DELETE CustomerView WHERE CustomerID = 'TEST2' AuthorNames warmodgenis Seqmna monacemta naxvisatvis: 1. Open Query Analyzer and connect to your local server. 2. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB CREATE VIEW AuthorNames AS SELECT FirstName, LastName FROM Authors 3. Execute the Transact-SQL statement. AuthorNames warmodgenis gamoyeneba monacemta naxvisatvis: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB SELECT * FROM AuthorNames ORDER BY LastName 2. Execute the Transact-SQL statement. AuthorNames warmodgenis Seqmna monacemta SetanisaTvis: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB INSERT AuthorNames VALUES ('William', 'Burroughs') 141

142 2. Execute the Transact-SQL statement. 3. In the Editor pane of the Query window, enter and execute the following Transact-SQL code: SELECT * FROM Authors 4. Scroll to the last row of the result set. AuthorNames warmodgenis Seqmna monacemta modifikaciisatvis: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB UPDATE AuthorNames SET FirstName = 'John' WHERE LastName = 'Burroughs' 2. Execute the Transact-SQL statement. 3. In the Editor pane of the Query window, enter and execute the following Transact-SQL code: SELECT * FROM AuthorNames 4. Scroll to the last row of the result set. AuthorNames warmodgenis Seqmna monacemta waslisatvis: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: USE BookShopDB DELETE AuthorNames WHERE LastName = 'Burroughs' 2. Execute the Transact-SQL statement. 3. In the Editor pane of the Query window, enter and execute the following Transact-SQL code: SELECT * FROM Authors 4. Scroll to the last row of the result set. AuthorNames warmodgenis wasla BookShopDB Si: 1. In the Editor pane of the Query window, enter the following Transact-SQL code: 142

143 USE BookShopDB DROP VIEW AuthorNames 2. Execute the Transact-SQL statement. 143

144 indeqsebi da gasarebebi indeqsebis tipebi ganirceva indeqsebis CLUSTERED an NONCLUSTERED tipebi, romlebic gvxvdeba CREATE TABLE, ALTER TABLE an CREATE INDEX brzanebebsi. indeqsis orive tipi struqturizebulia B-xis saxit. CLUSTERED tipis indeqsi Seicavs cxrilis Canawerebs B-xis umdables anu kenweroebis doneze, masin rodesac NONCLUSTERED tipis indeqsi Seicavs mxolod cxrilis Canawerebis CanarTebs B-xis umdables doneze. ufro met SemTxvevebSi unda Seiqmnas cxrilis klasterizebuli indeqsi, vidre araklasterizebuli indeqsi, radgan klasterizebuli indeqsis SemTxvevaSi xdeba monacemta sortireba, rac.ufro mizansewonili da efeqturia. musaoba SQL Enterprise Manager-Si: a) indeqsis Seqmna SQL Server Enterprise Manager - is sasualebit: 1. gavusvat Sesrulebaze SQL Server Enterprise Manager, vircevt servers, monacemta bazas da cxrils; 2. Right Click monisnul cxrilze. konteqstur meniusi vircevt: Design Table; 3. Click instrumenta panelis Rilakze Table and Index Properties; 4. Properties fanjarasi Index / Keys CanarTSi vawert New Rilakze; 5. Tu SemoTavazebuli indeqsi gvawyobs, mivirot, Tu ara masin Index name velsi Segvaqvs saxeli; 6. Column Name velsi svetebs, romlebic indeqssi CairTvebian; 7. davayenot sawiro drosebi da gadamrtvelebi, davxurot fanjara Close Rilakze dawerit; b) indeqsis Seqmna Create index Wizard - is sasualebit: 1. gavusvat Sesrulebaze SQL Server Enterprise Manager, vircevt servers, monacemta bazas da cxrils; 2. Click intrumentebis panelis Run a Wizard Rilakze; 3. obieqtebis xeze gavxsnat Database 4. gamovyot Create Index Wizard da vawert Ok Rilaks, Semdeg Next; 5. vircevt monacemta bazas, cxrils da vawert Next Rilaks; 144

145 gamodis arsebuli indeqsebis sia. vawert Next Rilaks; 6. vircevt svetebs, vawert Next Rilaks; 7. vircevt indeqsebis Tvisebebs, vawert Next Rilaks; 8. indeqss eniweba saxeli. vawert Rilakebs Finish da Ok. g) indeqsis Seqmna Index Tuning Wizard - is sasualebit. 1. gavusvat Sesrulebaze SQL Server Enterprise Manager, vircevt servers, monacemta bazas da cxrils; 2. Click intrumentebis panelis Run a Wizard Rilakze; 3. obieqtebis xeze gavxsnat Management. gamovyot Index Tuning Wizard da vawert Ok Rilaks, Semdeg Next; 4. vircevt servers, monacemta bazas. vawert Next Rilaks; 5. vayenebt gadamrtvels, vawert Next Rilaks; 6. vayenebt My workload file gadamrtvels. vircevt skriptis fails. d) indeqsebis asaxva 1. gavusvat Sesrulebaze SQL Server Enterprise Manager, vircevt servers, monacemta bazas da cxrils; 2. meniusi vircevt Tools / SQL Server Query Analyser; 3. vircevt monacemta bazas, brzanebit striqonsi vkrebt proceduris saxels: SP_HELPINDEX cxrilis saxeli an SP_STATISTICS cxrilis saxeli; 4. Click, Execute Query Rilakze an vawert F5 Rilaks. e) indeqsebis wasla 1. gavusvat Sesrulebaze SQL Server Enterprise Manager, vircevt servers, monacemta bazas da cxrils; 2. movnisnot cxrili. Right Click; konteqstur meniusi vircevt: Design Table; 3. Click instrumentta panelis Table and Index Properties Rilakze; 4. siasi movnisnot sawiro sveti da Click, Delete Rilakze; 5. vawert Close Rilakze. pirveladi da gare gasarebis damateba 1, 2, winas analogiurad; 145

146 3. SevirCioT sveti. Right Click; konteqstur meniusi vircevt: Setc Primary Key, an instrumentta panelis gasarebis Rilakze; 4. Tu pirvelad gasarebsi sxva velebic unda daematos, Properties fanjarasi Indexes / Keys CanarTSi, Selected Index siasi vircevt pirvelad gasarebs; 5. Column Name siasi Tanmimdevrobit vircevt svetebs, romelta damatebac gvsurs pirvelad gasarebsi; 6. vawert instrumentta panelis Save Rilakze. musaoba SQL Query Analyzer -Si: indeqsis Seqmna: CREATE [UNIQUE] [CLUSTERED NONCLUSTERED] INDEX index_name ON [table_name view_name](column_name [,...n]) [WITH [index_ property [,...n] ] [ON file_ group] garda amisa, brzaneba CREATE TABLE SeiZleba indeqsis SeqmnasTan dakavsirebuli iqnas: CREATE TABLE table_name (column_name data_type CONSTRAINT constraint_name [PRIMARY KEY UNIQUE] [CLUSTERED NONCLUSTERED] [WITH FILLFACTOR = fill_ factor ] [ON file_ group] ) pirveladi gasarebi yoveltvis Seicavs NOT NULL-s. CREATE TABLE table01 (column01 int 146

147 CONSTRAINT pk_column01 PRIMARY KEY) indeqsis administrireba. amocanata mxardawera Seicavs indeqsebis waslas, gadarqmevas da ardgenas. indeqsis wasla: DROP INDEX table_name.index_name view_name.index_name [,...n ] mravali indeqsis wasla : DROP INDEX table01.index01, view01.index02 indeqsis gadarqmeva: sistemuri stored procedure-is sp_rename-is gamoyenebit. = = = 'INDEX' a) klasterizebuli indeqsi : magaliti 1: magalitebi: CREATE TABLE dbo.persons ( personid smallint PRIMARY KEY NONCLUSTERED, firstname varchar(30), lastname varchar(40), socialsecuritynumber char(11) UNIQUE CLUSTERED ) magaliti 2: 1. SevitanoT da Sesrulebaze gavusvat Semdegi kodi : CREATE UNIQUE CLUSTERED INDEX CustomerOrder ON orders(customerid, orderid) WITH FILLFACTOR = kodi gavusvat Sesrulebaze. 147

148 3. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: ALTER TABLE orders ADD CONSTRAINT orders_pk PRIMARY KEY NONCLUSTERED (orderid) 4. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: ALTER TABLE bookorders ADD CONSTRAINT orderid_fk FOREIGN KEY (orderid) REFERENCES orders(orderid) 3. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: sp_helpindex orders sp_helpindex bookorders b) araklasterizebuli indeqsi: TiToeuli cxrilisatvis an warmodgenisatvis SeiZleba Seiqmnas 250 araklasterizebuli (an 249 araklas-terizebuli da erti klasterizebuli) indeqsi. indeqsebis Sesaxeb informaciis naxvisatvis gamoiyeneba sistemuri stored procedure: sp_help an sp_helpindex USE PUBS SELECT name, rows, rowcnt, keycnt from sysindexes WHERE name NOT LIKE '%sys%' ORDER BY keycnt monacemta bazis Northwind indeqsebis Tvisebebis naxva: 1. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 2. Query is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: sp_helpindex customers 3. vnaxot romeli indeqsi warmoadgens mowesrigebulad Customers cxrils. 4. vnaxot Customers cxrili Seicavs Tu ara Sedgenil indeqss. araklasterizebuli indeqsis Seqmna da testireba: 148

149 1. gavxsnat SQL Query Analyzer da davakavsirot lokalur servertan. 2. Query Analyzer -is redaqtoris fanjarasi SevitanoT Transact-SQL kodi: USE bookshopdb sp_helpindex books 4. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: CREATE NONCLUSTERED INDEX TitleSoldStatus ON books(title, sold) 4. Tu Sedegebi ar aisaxeba Query Analyzer-is panelze, masin click Show Execution Planze. 5. testirebisatvis SevitanoT da Sesrulebaze gavusvat Semdegi kodi : SELECT titleid, title, sold from books 6. vnaxot testirebis Sedegebi. indeqsebis gadarqmeva da wasla: 1. redaqtoris fanjarasi SevitanoT Semdegi kodi: = = 'INDEX' 2. kodi gavusvat Sesrulebaze. 3. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: DROP INDEX orders.in_customerorder, books.titlesoldstatus 5. SevitanoT da Sesrulebaze gavusvat Semdegi kodi: CREATE UNIQUE CLUSTERED INDEX orders_pk ON orders(orderid) WITH DROP_EXISTING 149

150 laboratoriuli samusao #11 SQL Server Uses an Index to Solve a Point Query SELECT * FROM Northwind.dbo.Products WHERE ProductID = 10 SQL Server Can Use Indexes When the Query Is Defined for a Range of Values -- Combining > or >= with < or <= SELECT * FROM Northwind.dbo.Products WHERE UnitPrice > 10 AND UnitPrice <= Using the BETWEEN operator SELECT * FROM Northwind.dbo.Customers WHERE PostalCode BETWEEN 'WX1'AND 'WXZZZZZ' -- Which is equivalent to: SELECT * FROM Northwind.dbo.Customers WHERE PostalCode >= 'WX1' AND PostalCode <= 'WXZZZZZ' -- Using the LIKE Operator with trailing wildcards SELECT * FROM Northwind.dbo.Customers WHERE CompanyName LIKE 'Hungry%' -- Which is equivalent to: SELECT * FROM Northwind.dbo.Customers WHERE CompanyName >= 'Hungry' AND CompanyName < 'HungrZ' SQL Server Uses an Index to Execute This Query That Joins Two Tables SELECT Products.ProductID, [Order Details].UnitPrice, [Order details].quantity FROM Products JOIN [Order Details] ON Products.ProductID = [Order Details].ProductID 150

151 WHERE Products.CategoryID = 1 SQL Server Can Use Indexes to Join Tables SELECT Products.ProductID, [Order Details].UnitPrice, [Order details].quantity FROM Products JOIN [Order Details]] ON Products.ProductID = [Order Details].ProductID SQL Server Can Use an Index to Avoid Access to Data Pages SELECT DISTINCT CategoryID FROM Products SQL Server Uses Unique Indexes to Check for Duplicate Values in INSERT and UPDATE Operations SET IDENTITY_INSERT Categories ON INSERT Categories (CategoryID, CategoryName, Description) VALUES (9, 'Liquors', 'Whiskies, Brandies and other Spirits') SET IDENTITY_INSERT Categories OFF SQL Server Can Use Indexes to Produce an Ordered Output SELECT ProductName, UnitPrice FROM Products ORDER BY ProductName ASC SQL Server Must Execute a SORT Process If None of the Indexes Available Matches the Ordering Criteria SELECT ProductName, UnitPrice FROM Products ORDER BY UnitPrice ASC 151

152 Creating an Index Is Easy Using the CREATE INDEX Statement CREATE INDEX ndx_customers_city ON Customers(City) You Can Create an Index on More Than One Column Using the CREATE INDEX Statement CREATE INDEX ndx_customers_company_phone ON Customers(CompanyName, Phone) CREATE INDEX ndx_customers_phone_company ON Customers(Phone, CompanyName) You Must Specify the CLUSTERED Keyword to Create a Clustered Index IF OBJECT_ID('OrderDetails') IS NOT NULL DROP TABLE OrderDetails -- Create a new table with the same structure and data -- as the Order Details table SELECT * INTO OrderDetails FROM [Order Details] -- Create a Clustered index on the new table CREATE CLUSTERED INDEX C_ORDER_DETAILS_ORDER_PRODUCT ON OrderDetails (OrderID, ProductID) You Must Execute the DROP INDEX Statement to Remove an Index from a Table You Must Specify the UNIQUE Keyword to Create a Unique Clustered Index CREATE UNIQUE CLUSTERED INDEX UC_ORDER_DETAILS_ORDER_PRODUCT ON OrderDetails (OrderID, ProductID) You Can Specify Descending or Ascending Order for Every Column in the Index Key 152

153 CREATE INDEX C_Products_Category_Price ON Products (CategoryID ASC, UnitPrice DESC) You Can Specify the NONCLUSTERED Keyword to Create a Nonclustered Index CREATE NONCLUSTERED INDEX C_ORDER_DETAILS_PRODUCT ON [Order Details] (ProductID) You Must Execute the DROP INDEX Statement to Remove an Index from a Table DROP INDEX [Order Details].C_ORDER_DETAILS_PRODUCT You Must Specifythe UNIQUE Keyword to Create a Unique Nonclustered Index IF OBJECT_ID('NewOrders') IS NOT NULL DROP TABLE NewOrders SELECT * INTO NewOrders FROM Orders CREATE UNIQUE NONCLUSTERED INDEX UNC_ORDERS_ORDERID ON NewOrders (OrderID) This Query Can Be Coveredby an Index on the Columns (City, CompanyName, ContactName) SELECT CompanyName, ContactName FROM Customers WHERE City = 'Madrid' This Query Can Be Covered by an Index on the Columns (City, CompanyName, ContactName) SELECT CustomerID, CompanyName, ContactName FROM Customers WHERE City = 'Madrid' This Query Can Be Solved by an Index on OrderID and Another Index on UnitPrice 153

154 SELECT OrderID, UnitPrice FROM [Order details] WHERE UnitPrice > 15 AND OrderID > You Can Modify Existing Indexes with the CREATE INDEX Statement and the DROP_EXISTING Option CREATE UNIQUE CLUSTERED INDEX UC_ORDER_DETAILS_ORDER_PRODUCT ON OrderDetails (OrderID, ProductID) WITH DROP EXISTING Use DBCC DBREINDEXto Rebuild All the Indexes of a Table DBCC DBREINDEX ('[Order details]') You Can Specify a New FILLFACTOR for an Existing Index with the CREATE INDEX Statement and the FILLFACTOR Option CREATE NONCLUSTERED INDEX OrderID ON [Order Details] (OrderID) WITH DROP_EXISTING, FILLFACTOR = 80 Use DBCC DBREINDEX to Rebuild All the Indexes of a Table with a Different FILLFACTOR DBCC DBREINDEX ('[Order details]', '', 70) You Can Specify a New FILLFACTOR for an Existing Index with the CREATE INDEX Statement and the FILLFACTOR Option, and Apply This FILLFACTOR to the Nonleaf-Level Pages with the PAD_INDEX Option CREATE NONCLUSTERED INDEX OrderID ON [Order Details] (OrderID) WITH DROP_EXISTING, FILLFACTOR = 80, PAD_INDEX Use DBCC DBREINDEX to Pack the Data Pages by Rebuilding the Clustered Index with a FILLFACTOR of

155 DBCC DBREINDEX ('Products', PK_Products, 100) Use DBCC SHOW_STATISTICS to Get Information About Index Statistics DBCC SHOW_STATISTICS (Products, SupplierID) By Using sp_dboption, It Is Possible to Avoid Automatic Statistics Creation and Maintenance for the Entire Database EXEC sp_dboption 'Northwind', 'auto create statistics', 'false' EXEC sp_dboption 'Northwind', 'auto update statistics', 'false' PRINT 'After changing to manual statistics maintenance' EXEC sp_dboption 'Northwind', 'auto create statistics' EXEC sp_dboption 'Northwind', 'auto update statistics' It Is Possible to Create Statistics on Nonindexed Columns CREATE STATISTICS stproductsstock ON Products(UnitsInStock) CREATE STATISTICS stproductsstockorder ON Products(UnitsInStock, UnitsOnOrder) EXEC sp_createstats Use the sp_helpstats System Stored Procedure to Get Information About Statistics EXEC sp_helpstats Use the sp_helpindex System Stored Procedure to Retrieve Information About Indexes in a Table EXEC sp_helpindex customers Use the INDEXPROPERTY Function to Retrieve Information About Any Index SELECT INDEXPROPERTY(OBJECT_ID('Products'), 'PK_Products', 'IndexDepth') AS 'Index Levels' SELECT CASE 155

156 INDEXPROPERTY(OBJECT_ID('Products'), 'PK_Products', 'IsClustered') WHEN 0 THEN 'No' ELSE 'Yes'END as 'Is Clustered' SELECT CASE INDEXPROPERTY(OBJECT_ID('Products'), 'PK_Products', 'IsStatistics') WHEN 0 THEN 'No' ELSE 'Yes'END as 'Is Statistics only' SELECT CASE INDEXPROPERTY(OBJECT_ID('Products'), 'PK_Products', 'IsUnique') WHEN 0 THEN 'No' ELSE 'Yes'END as 'Is Unique' It Is Possible to Create Indexes on Computed Columns ALTER TABLE [order details] ADD SalePrice AS (UnitPrice * Quantity) CREATE INDEX ndxsale ON [order details] (SalePrice) In SQL Server 2000, You Can Create Indexes on Views CREATE VIEW Customers_UK WITH SCHEMABINDING AS SELECT CustomerID, CompanyName, ContactName, Phone FROM dbo.customers WHERE Country = 'UK' SELECT CustomerID, CompanyName, ContactName, Phone FROM Customers WHERE Country = 'UK' AND CompanyName like 'C%' CREATE UNIQUE CLUSTERED INDEX CustUK ON Customers_UK (CustomerID) CREATE NONCLUSTERED INDEX CustUKCompany ON Customers_UK (CompanyName) SELECT CustomerID, CompanyName, ContactName, Phone FROM Customers WHERE Country = 'UK' AND CompanyName like 'C%' You Can See How to Optimize the Following Query Using Index Tuning Wizard SELECT OD.OrderID, O.OrderDate, C.CompanyName, P.ProductName, OD.UnitPrice, OD.Quantity, OD.Discount FROM [Order Details] AS OD 156

157 JOIN [Orders] AS O ON O.OrderID = OD.OrderID JOIN [Products] AS P ON P.ProductID = OD.ProductID JOIN [Customers] AS C ON C.CustomerID = O.CustomerID WHERE Country = 'UK' These Are the Recommendations of the Index Tuning Wizard to Optimize the Query of Listing 6.35 /* Created by: Index Tuning Wizard */ /* Date: 25/10/2000 */ /* Time: 23:36:33 */ /* Server Name: BYEXAMPLE */ /* Database Name: Northwind */ USE [Northwind] go SET QUOTED_IDENTIFIER ON SET ARITHABORT ON SET CONCAT_NULL_YIELDS_NULL ON SET ANSI_NULLS ON SET ANSI_PADDING ON SET ANSI_WARNINGS ON SET NUMERIC_ROUNDABORT OFF go as bit BEGIN TRANSACTION = 0 DROP INDEX [dbo].[orders].[shippostalcode] DROP INDEX [dbo].[orders].[shippeddate] DROP INDEX [dbo].[orders].[customersorders] DROP INDEX [dbo].[orders].[orderdate] DROP INDEX [dbo].[orders].[customerid] DROP INDEX [dbo].[orders].[shippersorders] DROP INDEX [dbo].[orders].[employeesorders] DROP INDEX [dbo].[orders].[employeeid] CREATE NONCLUSTERED INDEX [Orders7] ON [dbo].[orders] ([OrderID] ASC, [CustomerID] ASC, [OrderDate] ASC ) <> 0 ) = 1 = 0 ) COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION BEGIN TRANSACTION = 0 DROP INDEX [dbo].[order Details].[ProductID] DROP INDEX [dbo].[order Details].[orderID] DROP INDEX [dbo].[order Details].[price] 157

158 DROP INDEX [dbo].[order Details].[OrdersOrder_Details] DROP INDEX [dbo].[order Details].[ProductsOrder_Details] DROP INDEX [dbo].[order Details].[ndxSale] = 0 ) COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION BEGIN TRANSACTION = 0 DROP INDEX [dbo].[customers].[region] DROP INDEX [dbo].[customers].[companyname] DROP INDEX [dbo].[customers].[contact] DROP INDEX [dbo].[customers].[ndx_customers_city] DROP INDEX [dbo].[customers].[postalcode] DROP INDEX [dbo].[customers].[city] = 0 ) COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION BEGIN TRANSACTION = 0 DROP INDEX [dbo].[products].[c_products_category_price] DROP INDEX [dbo].[products].[categoriesproducts] DROP INDEX [dbo].[products].[suppliersproducts] DROP INDEX [dbo].[products].[categoryid] DROP INDEX [dbo].[products].[productname] DROP INDEX [dbo].[products].[supplierid] = 0 ) COMMIT TRANSACTION ELSE ROLLBACK TRANSACTION /* Statistics to support recommendations */ CREATE STATISTICS [hind_ _1a_2a_3a_4a_5a] ON [dbo].[order details] ([OrderID], [ProductID], [UnitPice], [Quantity], [Discount]) 158

159 tranzakciebi da blokirebebi tranzakcia. mravalmomxmarebliani danartis SemuSavebis dros monacemta bazis momsaxurebis TvalsazrisiT didi mnisvneloba eniweba tranzakciebsa da blokirebebs. tranzakcia (transaction) ganixileba rogorc operaciata erti mtliani logikuri bloki, logikuri samusaos erteuli, romelic warmoadgens mb-is erti SeTanxmebuli mdgoma-reobis meoresi gardaqmnas. tranzakcia aris ardgenis erteulic operaciis warumatebeli Sesrulebis SemTxvevaSi. aseti ganaxlebis (damatebis, amogdebis da sxv.) Sedegad SesaZloa moxdes mb_is SeTanxmebuli mdgomareobis darrveva. am SemTxvevaSi unda Sesruldes Catare-buli ganaxlebis anulireba. amgvarad, tranzakcia an sruldeba mtlianad an sruliad uqmdeba. ZiriTadi motxovnebi tranzakciebis mimart: * atomaruloba anu ganuyofeloba ( Atomicity) _ sruldeba an yvelaferi an araferi. * SeTanxmebuloba (Consistency)_ gadayavs mb erti SeTanxmebuli mdgomarebidan meoresi. * izolacia (Isolation)_ tranzakciebi gancalkevebuli arian ertmanetisagan. * xanrzlioba (Durability)_ sanam tranzakcia sruldeba, misi ganaxlebani inaxeba. tranzakciis arwer a xdeba Semdegi gasareburi sityvebis mesveobit: BEGIN TRAN[SACTION] tranzakciis Seqmna; COMMIT TRAN[SACTION] tranzakciis Sesruleba; ROLLBACK TRAN[SACTION] tranzakciis ukuqceva anu ukusvla. tranzakciis magaliti (fsevdokodi) moyvanilia naxazze: BEGIN TRANSACTION; INSERT ( { S#: S5, P#: P1, QTY: 1000 } ) INTO SP; IF warmoisva Secdoma THEN TO UNDO; UPDATE P WHERE P# = P1 TOTQTY := TOTQTY ; IF warmoisva Secdoma THEN TO UNDO; COMMIT TRANSACTION; TO FINISH; UNDO : ROLLBACK TRANSACTION; FINISH : RETURN; 159

160 magaliti: BEGIN TRAN ChangeNameAllCustomers UPDATE Customers SET CompanyName = CompanyName WHERE COUNTRY = 'USA' SELECT [Current LSN], Operation, [Transaction Name] FROM ::fn_dblog(null, NULL) COMMIT TRAN BEGIN TRAN ChangeUnitsInStock_1_10_20 WITH MARK UPDATE Products SET UnitsInStock = UnitsInStock * 1.1 WHERE ProductID in (1, 10, 20) COMMIT TRAN aracxadi saxit tranzakcia moicema SET operaciis sasualebit: SET IMPLICIT_TRANSAKTION ON OFF. ANSI standartsi mocemulia tranzakciebis izolaciis otxi done: done 0. No trashing of data (monacemta ertdrouli modifikaciis akrzalva), roca or process ekrzaleba ertidaigive monacemis Secvla. done 1. No dirty reads (e.w. `WuWyiani~ wakitxvis akrzalva), rodesac ikrzaleba monacemta wakitxva, romlebic mocemul momentsi modificirdebian. done 2. No nonrepeatable reads (araganmeorebadi wakitxvis akrzalva), rodesac erti tranzakciis SigniT monacemta or wakitxvas Soris SualedSi ikrzaleba mati ganaxleba sxva tranzakciebsi anu ikrzaleba operacia UPDATE. done 3. No phantoms (ikrzaleba fantomebis gamocena). damatebit UPDATE sa ikrzaleba operaciebi INSERT da DELETE. naxazze ganxilulia tranzakciebis xuti varianti sistemis avariul mtyunebaze. 160

161 nax cxadia, rom sistemis gadatvirtvis dros T3 dat5 tipis tranzakciebi unda gauqmdes, xolo T2 da T4 tipis tranzakciebi xelmeored Sesruldes. am SemTxvevaSi sruldeba Semdegi bijebi: 1. iqmneba ori sia (UNDO da REDO). 2. registraciis failsi (JurnalSi) xdeba Zebna sakontrolo wertilis Canaweridan dawyebuli. 3. Tu registraciis failsi armocnda Canaweri tranzakciis dawyebis Sesaxeb, masin es tranzakcia Seitaneba UNDO siasi. 4. Tu registraciis failsi armocenilia Canaweri is damtavrebis Sesaxeb, es tranzakcia Seitaneba REDO siasi. 5. registraciis failis bolos xdeba UNDO da REDO siebis analizi REDO siasi T2 da T4 tipis tranza-kciebis da UNDO siasi T3 da T5 tipis tranzakciebis identifikaciisatvis. 161

162 sistemebi, sadac tranzakciebi urtiertqmedeben resursebis mravaldonian administratorebtan (magalitad, ori sxvadasxva mbms), unda gamoiyenebodes protokoli e.w. orfaziani fiqsacia _ mosamzadebeli da fiqsaciis fazebit. da bolos, Tu SemmuSavebelma tranzakcia Riad datova, serveris Tavidan gasvebisas Sesruldeba ukusvla da mb-s ardgena im mdgomareobasi, romelsic imyofeboda proceduris musaobis dawyebis win. blokireba. ertidaigive monacemebtan ertdroulad mravali tranzakciis damusavebis SemTxvevaSi konfliqturi situaciebis Tavidan asacileblad aucilebelia paralelizmis martvis metodebis gamoyeneba. yvelaze gavrcelebuli metodia blokireba, romlis ZiriTadi idea martivia: im SemTxvevaSi, roca garkveuli tranzakciis SesrulebisaTvis aucilebelia, rom romelirac obieqti ar icvlebodes e.i. iyos blokirebuli. amgvarad, blokirebis efeqti mdgomareobs imasi, rom am obieqttan mimartva sxva tranzakciiebis mxridan iqnas blokirebuli. ganirceva ori tipis blokireba: monopoluri anu urtiertmimartvis garese blokireba (X_blokireba) da blokireba urtiertmimartvit (S_ blokireba). Tu tranzakcia romelime obieqts uketebs S_ bloki-rebas, masin sxva tranzakciiebsac SeuZliaT am obieqtze S_blokirebis (magram ara X_blokirebis) gaketeba. Tu tranzakcia raime obieqtze aketebs X_blokirebas, masin vercerti sxva tranzakcia am obieqtze veranair sxva blokirebas verar gaaketebs. Caweris blokirebis (Xlocks-eXclusive locks) da wakitxvis blokirebis (Slocks-Shared locks) Tavsebadobis matricis (nax ) safuzvelze warmoebs monacemebtan mimartvis protokoli. 162

163 nax simbolo N _ arnisnavs konfliqtur situacias (tranzakcia ar kmayofildeba, gadadis lodinze). simbolo Y _ arnisnavs srul Tavsebadobas. samwuxarod, zogjer blokirebis gamoyenebas mohyveba e.w. Cixuri situacia, roca ori an meti tranzakcia ertdroulad imyofeba lodinis mdgomareobasi. amastan TiToeuli elodeba sxva tranzakciis Sesrulebis dam-tavrebas. mis gadasawyvetad xdeba erterti tranzakciis Sesrulebis gauqmeba. aseve blokirebebic ganirceva doneebis mixedvit: * RID (striqonis identifikatori) gamoiyeneba cxrilis SigniT calkeuli striqonis blokirebisatvis. * Key (gasarebi) gamoiyeneba indeqsis SigniT blokirebisatvis Tanmimdevrul tranzakciebsi gasarebebis diapazonis dacvisatvis. * Page (gverdi) gamoiyeneba 8 kb gverdis monacemebis an indeqsebis blokirebisatvis. * Extent (eqstenti) _ gamoiyeneba 8 kb gverdis monacemebisagan an indeqsebisagan Semdgari jgufis blokirebisatvis. * Table (cxrili) _ gamoiyeneba cxrilebis (monacemebisa da indeqsebis CaTvliT) blokirebisatvis. * DB (mb) gamoiyeneba blokirebisatvis monacemta bazis doneze. ukusvlis SemTxvevaSi Secdomebis Tavidan asacileblad gamoiyeneba: saxelobiti tranzakciebi ( named) da Senaxvis wertilebi (SavePoints). am ukanasknelis Sesaqmnelad gamoiyeneba: SAVE TRANSACTION tranzakciis-saxeli. blokirebis Sesaxeb informaciis asaxvisatvis gamoiyeneba SQL Server Enterprise Manager an Sesanaxi procedura SP_LOCK. ganvixilot pirveli varianti: 1. gavusvat SQL Server Enterprise Manager programuli jgufidan Microsoft SQL Servers; 2. vircevt servers; 3. serveris xeze gavxsnat folderi Management; 4. gavxsnat Current Activity; 5. mimdinare blokirebis sanaxavad gavxsnat erterti: 163

164 Locks / Process ID; Locks / Object; 5. Tu procesis amogdeba gvinda, Current Activity fanjarasi vawert panelis Rilaks Kill Process; Yes. SP_LOCK- is SemTxvevaSi: USE master EXEC sp_lock danartsi monacemta garkveuli krebulis cxadi saxit blokirebisatvis SELECT instruqciasi gamoiyeneba optimizatoris Semdegi parametrebi: NOLOCK motxovnasi `WuWyiani~ Canaweris wakitxvis sasualebas izleva. `WuWyiani~ hqvia Canawers, romlebic amorcevis momentsi sxva momxmareblebis mier aris ganaxlebuli an waslili. HOLDLOCK monacemta amorcevis momentsi gayofili blokirebuli gverdis gamozaxebis sasualebas izleva. TABLOCK _ instruqciis mteli drois ganmavlobasi blokirdeba instruqciasi mititebuli mteli cxrili an cxrilebi. TABLOCKX axdens monopolur blokirebas tranzakciis Sesrulebis mteli drois ganmavlobasi. 164

165 laboratoriuli samusao #12 magalitebi: USE Pubs SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION SELECT Au_lname FROM Authors WITH (NOLOCK) Use sp_lock to Get Information About Lockings BEGIN TRAN money = AVG(UnitPrice) FROM [Order Details] (REPEATABLEREAD) WHERE ProductID = 37 UPDATE Products SET UnitPrice WHERE ProductID = 37 EXECUTE sp_lock EXECUTE ROLLBACK TRAN Use LOCK_TIMEOUT to Control How Much Time a Connection Will Wait for Locks to Be Released BEGIN TRANSACTION SELECT * FROM Products (HOLDLOCK) 165

166 SET LOCK_TIMEOUT 2000 UPDATE Products SET UnitPrice = UnitPrice * 0.9 Examples of Shared Locks BEGIN TRAN SELECT OBJECT_ID('Order details') as 'Order details' SELECT OBJECT_ID('Orders') as 'Orders' SELECT OBJECT_ID('Products') as 'Products' PRINT 'Initial lock status'+ CHAR(10) EXEC sp_lock SELECT MAX(OrderID) FROM Orders WHERE CustomerID = 'ALFKI' PRINT CHAR(10) + 'Lock status after SELECT'+ CHAR(10) EXEC sp_lock INSERT [Order Details] (OrderID, ProductID, Unitprice, Quantity, Discount) SELECT (SELECT MAX(OrderID) FROM Orders (HOLDLOCK) WHERE CustomerID = 'ALFKI'), ProductID, UnitPrice, 10, 0.1 FROM Products (REPEATABLEREAD) WHERE ProductName = 'Tofu' PRINT CHAR(10) + 'Lock status after INSERT'+ CHAR(10) EXEC sp_lock 166

167 ROLLBACK TRAN PRINT CHAR(10) + 'Lock status after ROLLBACK'+ CHAR(10) EXEC sp_lock Modifying Data Produces Exclusive Locks BEGIN TRAN SELECT OBJECT_ID('Products') as 'Products' PRINT 'Initial lock status'+ CHAR(10) EXEC sp_lock UPDATE Products SET UnitPrice = UnitPrice WHERE ProductID = 28 PRINT CHAR(10) + 'Lock status after the mock UPDATE'+ CHAR(10) EXEC sp_lock UPDATE Products SET UnitPrice = UnitPrice * 1.5 WHERE ProductID = 35 PRINT CHAR(10) + 'Lock status after the real UPDATE'+ CHAR(10) EXEC sp_lock ROLLBACK TRAN Update Locks BEGIN TRAN SELECT OBJECT_ID('Products') as 'Products' PRINT 'Initial lock status'+ CHAR(10) EXEC sp_lock SELECT ProductID, ProductName, UnitPrice FROM Products (UPDLOCK) WHERE ProductID = 28 PRINT CHAR(10) + 'lock status after SELECT'+ CHAR(10) EXEC sp_lock /* 167

168 UPDATE Products SET UnitPrice = UnitPrice WHERE ProductID = 28 */ PRINT CHAR(10) + 'lock status after UPDATE from Connection B'+ CHAR(10) EXEC sp_lock UPDATE Products SET UnitPrice = UnitPrice WHERE ProductID = 28 PRINT CHAR(10) + 'Lock status after the mock UPDATE'+ CHAR(10) EXEC sp_lock ROLLBACK TRAN SQL Server Uses Schema Modification Locks to Protect Objects During Creation or Modification BEGIN TRAN CREATE TABLE TestSchema (ID int) SELECT object_name(1) AS ID1 SELECT object_name(2) AS ID2 SELECT object_name(3) AS ID3 SELECT Object_ID('TestSchema') AS TestSchemaID EXEC sp_lock ROLLBACK TRAN Use the SERIALIZABLE Locking Hint to Force Range Locks BEGIN TRAN SELECT OBJECT_ID('Products') as 'Products' PRINT 'Initial lock status'+ CHAR(10) 168

169 EXEC sp_lock SELECT ProductID, ProductName, UnitPrice FROM Products (SERIALIZABLE) WHERE CategoryID = 3 PRINT CHAR(10) + 'lock status after SELECT'+ CHAR(10) EXEC sp_lock SERIALIZABLE doneze Canaweri SeiZleba Setanili iqnas authors cxrilsi tranzakciis SesrulebiT: USE pubs SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION SELECT au_lname FROM authors To determine the transaction isolation level currently set, use the DBCC USEROPTIONS statement, for example: USE pubs SET TRANSACTION ISOLATION LEVEL REPEATABLE READ DBCC USEROPTIONS Set Option Value Textsize 4096 Language Dateformat us_english mdy Datefirst 7 169

170 isolation level repeatable read For example, if the transaction isolation level is set to SERIALIZABLE, and the table-level locking hint NOLOCK is used with the SELECT statement, key-range locks typically used to maintain serializable transactions are not taken. USE pubs SET TRANSACTION ISOLATION LEVEL SERIALIZABLE BEGIN TRANSACTION SELECT au_lname FROM authors WITH (NOLOCK) The locks generated are: EXEC sp_lock spid dbid ObjId IndId Type Resource Mode Status DB S GRANT DB S GRANT DB S GRANT DB S GRANT DB S GRANT TAB Sch-S GRANT DB S GRANT TAB IS GRANT SELECT object_name( ) 170

171 authors The only lock taken that references authors is a schema stability (Sch-S) lock. In this case, serializability is no lo nger guaranteed. 171

172 SQL Server - is administrireba mb-s birtvis martva moitxovs garkveul droit danaxarjebs. administrirebis operaciata SesrulebiT SeiZleba momxmarebeltatvis pasuxis drois optimizeba. sakontrolo wertilebi (checkpoints) - aris funqciebi, romlebsac sistema asrulebs drois mocemuli momentisatvis cvlilebata an konfiguraciis parametrebis Caweris miznit. `binzuri~ gverdebi (dirty pages) - warmoadgens gverdebs, romelic Seicavs, jer kidev diskze Seunaxav, ganaxlebul monacemebs. Cveulebriv, sakontrolo wertilebi yovel 60 wamsi iniciirdeba. CHECKPOINT brzaneba sruldeba mxolod mimdinare mb-satvis e.i. mb-s doneze. Tu sistemasi gaxsnilia ramdenime mb, masin es brzaneba unda Sesruldes yoveli matganisatvis. 1. SQL Server Enterprise Manager - is fanjarasi vircevt mb-s; 2. marjvena Click-iT mb-ze, konteqstur meniusi vircevt Edit; 3. gadavdivart Options CanarTze; 4. Tu davayenebt drosas Truncate Log on Checkpoint, masin tranzakciebis Jurnali avtomaturad mokldeba sakontrolo wertilis Sesrulebis dros. Tu drosa moxsnilia, masin replikaciac ar sruldeba, sistema amoklebs tranzakciebis Jurnals bolo warmatebulad dasrulebul tranzakciamde. mb-s mtlianobis Semowmebis sasualeba (Database Consistency Checker, DBCC) gamoiyeneba serversi mb-s mtlianobis Sesamowmeblad. DBCC utilitas gamoyenebisatvis unda gavarciot ori piroba: 1) sawiroa minimaluri aqtivobis uzrunvelyofa; 2) aucilebelia mb-stan monopoluri midgoma, rac xorcieldeba proceduris SP_DBOPTION [ mb-s_saxeli ], single user, True mesveobit, romelsac mb-s musaoba gadayavs ertmomxmareblian rejimsi. DBCC instruqciebi, romlebic gamoiyeneba sisworis SemowmebisaTvis: NEWALLOC da CHECKALLOC. isini praqtikulad identurni arian. ubralod CHECKALLOC - is gamoyeneba iwvevs sistemuri procesis gacerebas, roca DBBC Secdomas poulobs. sintaqsisi: DBCC CHECKALLOC ( mb-s-saxeli [, NOINDEX 172

173 ] {REPAIR_ALLOW_DATA_LOOS REPAIR_FAST REPAIR_REBUILD} ) [WITH {ALL_ERRORMSGS NO_INFOMSGS}] instruqcia CHECKDB amowmebs yvela cxrils, monacemta asocirebul gverdebs, indeqsebs da macveneblebs: DBCC CHECKDB ( mb-s-saxeli [, NOINDEX {REPAIR_ALLOW_DATA_LOSS REPAIR_FAST REPAIR_REBUILD} ] ) [ WITH (ALL_ERRORMSGS NO_INFOMSGS}] SHRINKDATABASE (SHRINKDB) instruqcia mb-s Seqmnisas itxovs realurad sawiro diskur sivrces: DBCC SHRINKDATABASE (mb-s-saxeli [, axali-zoma_procentebsi] [, {NOTRUNCATE TRUNCATEONLY}] igive samusao sruldeba SQL Server Enterprise Manager-iTac: 1. marjvena click mb-ze, konteqstur meniusi vircevt Task / Shrink Database; 2. fanjarasi SemoTavazebulia sxvadasxva varianti: - Shrink Database by (%) - Remove as much free space as possible drosit: Periodically check to see if the database disk space can be shrink sistema periodulad miadevnebs kontrols mb-s zomebs. zogjer aucilebelia raime parametris, romelic ar miekutvneba SQL Server-is standartul obieqtebs, Semowmeba, rac trasirebis drosebis ( trace flags) daxmarebit xdeba: 1. marjvena Click serveris saxelze. konteqstur meniusi vircevt Properties; 2. General CanarTSi vawert Startup Parameters Rilaks, ixsneba Server Parameters fanjara. monacemta dakargvisagan dasacavad SQL Server-s gaacnia Semdegi xerxebi: -fizikuri dublireba; mb-s da tranzakciebis Jurnalis rezervireba drois intervalebsi. mb-s rezervirebisatvis: 1. vircevt mb-s. vxsnit konteqstur menius; 173

174 2. vircevt Tools / Backup Database an Tasks / Backup Database; 3. Backup fanjarasi General CanarTSi vircevt rezervirebis tips: Database-Complete; Database-Differential; Transaction log; File and filegroup; 4. vircevt fails an mowyobilobas, sadac moxdeba kopireba: vawert Add. Choose Backup Destination fanjarasi vircevt fails an Backup Device; 5. SeiZleba axali mowyobilobis (New Backup Device) SerCevac; 6. Ok. sistema qmnis axal mowyobilobas da asaxavs mas siasi Destination velsi; 7. Semdegi jgufi (Overwrite) parametrebisa sarezervo aslis mowyobilobaze Senaxvis erterti rejimis arcevis sasualebas izleva: * Append to media - damateba mowyobilobasi; * Overwrite existing media - mowyobilobis gadawera; 8. Schedule drosit vircevt an avtomatur an ertdroul (xelit) rezervirebas. avtomaturis dros Cndeba Edit Schedule fanjara, sadac moicema ganrigis saxeli da tipi. darezervebuli aslidan informaciis ardgena: 1. gavxsnat Backup Devices saqaralde; 2. marjvena Click mowyobilobis saxelze. konteqstur meniusi vircevt Properties brzanebas; 3. fanjarasi vawert View Contents Rilaks; 4. marjvena Click mb-ze, konteqstur meniusi vircevt Task / Restore Backup; 5. Restore Database fanjarasi, Camoxsnad siasi Use backups from database vircevt monacemta bazas; 6. mocemulia ardgenis variantebi: - Restore database and transaction logs; - Restore filegroups or files; - Restore backup sets from device(s); Semdeg vircevt (Backup Set Type) Sesabamis ardgenis rejims, (Tu SerCeulia Restore specified backup set gadamrtveli) da Ok. 174

175 informaciis gadacema SQL Server-dan / Si 1. vircevt mb-s wyaros; 2. Tools / Data Transformation Servoces / Import into SQL an / Export from SQL; 3. vircevt mb-s monacemta mimrebs, Tu gvinda axali mb-s Seqmna Camoxsnad Database siasi vircevt New brzanebas; 4. Create Database fanjarasi ganvsazrvravt saxels, sawyis zomas da tranzakciebis Jurnals; 5. monacemta transformaciisatvis moicema ori varianti: - Copy table(s) from the source database; - Use a query to specify the data to transfer; 6. pirvel SemTxvevaSi vircevt cxrilebs, romelta monacemebi unda sxvagan SevinaxoT. Tu sawiroa yoveli cxrilis garkveuli svetebis amorceva, amisatvis vawert `...~ -s, Transform svetsi; 7. Column Mapping and Transformations fanjarasi Transformations CanarTSi vawert Advanced Rilaks; 8. Advanced Transformations Properties fanjarasi mocemulia sami varianti: - Default Transformation Flags-all possible conversions are allowed; - Require exact match between source and destination (datatype, size, precision, scale, nullability); - custom Transformation Flags; 9. Semdeg fanjarasi Segvizlia davayenot Semdegi drosebi: - Run Immediately; - Create Replication Publication; - Save Package on SQL Server. am SemTxvevaSi vayenebt drosas: - Schedule DTS Package for later execution da vawert `...~-s, rata SevirCioT dro, roca es unda gaketdes; 10. Finish. 175

176 laboratoriuli samusao #13 musaoba SQL Enterprise Manager-Si: monacemta bazis backup Seqmna 1. gavxsnat serverta jgufi da Semdgom serveri. 2. gavxsnat Databases, marjvena-click monacemta bazaze, punqtze All Tasks da Semdeg click Backup Database. 3. Name velsi vkreft backup-is saxels, Description-Si ki mis arweras. 4. Backup-is qves click Database - complete. 5. Destination-is qves click Tape an Disk da Semdeg vaketebt backup-is arweras. 6. Overwrite-is qves sruldeba erterti Semdegi : Click Append to media. Click Overwrite existing media. 7. backup-is Semdgomi operaciebis dagegmvisatvis vircevt Schedule-is check box: vircevt Verify backup upon completion-is check box. vircevt Eject tape after backup-is check box. vircevt Check media set name and backup set expiration-is check box. Media set name-si vkreft mediis saxels, romelic gamoiyeneba backup operaciebis dros. 8. backup media-is pirveli gamoyenebis an mediis saxelis Secvlis SemTxvevaSi Media set labels-is qves vircevt Initialize and label media-is check box da vkreft mediis saxelsa da mis arwerilobas. database backup-is ardgena 1. gavxsnat serverta jgufi da Semdgom serveri. 176

177 2. gavxsnat Databases, marjvena-click monacemta bazaze, punqtze All Tasks da Semdeg click Restore Database. 3. Restore as database-is velsi vkreft an vircevt monacemta bazis saxels. 4. Click Database. 5. First backup to restore-is siasi click backup set to restore-ze. 6. Restore-is siasi click database backup to restore-ze. 7. click Options tab-ze da sruldeba erterti Semdegi : Restore as -Si vkreft yoveli monacemta bazis saxelsa da gantavsebis adgils, romlistvisac Seqmnilia rezervi. Click Leave database operational. No additional transaction logs can be restoredze Tu ar arsebobs tranzakciis Jurnalisa da monacemta bazis rezervsi cvlileba. Click Leave database nonoperational, but able to restore additional transaction logs Tu arsebobs tranzakciis Jurnalisa da monacemta bazis rezervsi cvlileba. diferencirebuli monacemta bazis backup-is Seqmna 1. gavxsnat serverta jgufi da Semdgom serveri. 2. gavxsnat Databases, marjvena-click monacemta bazaze, punqtze All Tasks da Semdeg click Backup Database. 3. Name velsi vkreft backup-is saxels, Description-Si ki mis arweras. 4. Backup-is qves click Database - differential. 5. Destination-is qves click Tape an Disk da Semdeg vaketebt backup-is arweras. 6. Overwrite-is qves sruldeba erterti Semdegi : Click Append to media. 177

178 Click Overwrite existing media. 7. vircevt Schedule check box. 8. click Options tab da sruldeba erterti Semdegi: vircevt Verify backup upon completion check box. vircevt Eject tape after backup check box. vircevt Check media set name and backup set expiration check box. Media set name-si vkreft mediis saxels, romelic gamoiyeneba backup operaciebis dros. 9. mediis rezervis pirveli gamoyenebis an mediis saxelis Secvlis SemTxvevaSi Media set labels-is qves vircevt Initialize and label media-is check box da vkreft mediis saxelsa da mis arwerilobas. diferencirebuli monacemta bazis rezervis ardgena 1. gavxsnat serverta jgufi da Semdgom serveri. 2. gavxsnat Databases, marjvena-click monacemta bazaze, punqtze All Tasks da Semdeg click Restore Database. 3. Restore as database-is velsi vkreft an vircevt monacemta bazis saxels. 4. Click Database. 5. First backup to restore-is siasi click database backup to restore-ze. 6. Restore-is siasi click differential backup to restore-ze. 7. click Options tab-ze da sruldeba erterti Semdegi : Click Leave database operational. No additional transaction logs can be restored Tu tranzakciis Jurnalis rezervsi ar aris cvlileba. Click Leave database nonoperational, but able to restore additional transaction logs Tu tranzakciis Jurnalis rezervsi aris cvlileba. 178

179 funqciaa. SQL Server - is usafrtxoebis sistema monacemta Sida da gare dacva monacemta bazis administratoris erterti ZiriTadi nax klient/serveris sistemasi usafrtxoeba realizdeba sami xerxit: - standartuli usafrtxoeba. am SemTxvevaSi SQL Server-ze sruldeba momxmareblis autentifikacia da sistemasi Sesvlaze SezRudvebis dadeba; - integrirebuli usafrtxoeba. am rejimsi musaobisas momxmareblis mimartvis sakitxebs wyvets Windows NT da usafrtxoeba xorcieldeba mimartvis kontrolis siis (Access Control List, ACL) daxmarebit. - Sereuli usafrtxoeba. igi warmoadgens standartuli da integrirebuli usafrtxoebis kombinacias. amgvarad, monacemta bazebis dacva xdeba rogorc operaciuli sistemis doneze, ise TviTon SQL Server is mesveobit (nax ). 179

180 nax SQL Server-Si momxmareblis servertan mierteba xorcieldeba ori variantit: * Use Windows NT authentication - mierteba Windows NT momxmareblis saxelit; * Use SQL Server authentication - mierteba SQL Server-is saxelit. SQL Server-s gaacnia momxmareblis biujetis ori done: I. momxmareblis identifikatori (Login) anu sistemasi Sesvla. sistemasi yvela Sesasvleli inaxeba mtavari monacemta bazis Master cxrilsi SYSLOGINS. II. TviTon `momxmarebeli~ (users) anu obieqtebi, romelta daxmarebit SQL Server mimartvis uflebebs martavs. yvela daregistrirebuli obieqti-momxmarebeli inaxeba yoveli monacemta bazis cxrilsi SYSUSERS, romeltac gaacniat mimartvis ufleba. SQL Server - Si arsebobs ori standartuli identifikatori: SA da BUILTIN / Administrators. SA miewereba rols sysadmin da gaacnia absoluturi uflebebi. BUILTIN / Administrators uzrunvelyofs serverisadmi mimartvas Windows NT administratuli jgufis yvela wevrisatvis. momxmareblis identifikatoris Sesaqmnelad sawiroa: 1. SQL Server Enterprise Manager-is gaaqtiureba; 2. vircevt servers; 3. marjvena Click, Logins saqaraldeze da konteqstur meniusi vircevt New Login; 180

181 4. General CanarTSi: Segvyavs momxmareblis identifikatori, vircevt enas da mb-s; 5. Tu vircevt gadamrtvels Windows NT Authentication da domens siasi Domain, masin SQL Server operaciul sistemasi momxmareblis Sesvlis Semdeg damatebit Semowmebas arar Caatarebs. (Grant Access - nebadartulia, Deny Access - akrzalulia). Tu vircevt gadamrtvels SQL Server Authentication, masin sistema aketebs Semowmebas; 6. Server Roles CanarTSi TiToeuli momxmareblisatvis ganvsazrvravt uflebebs. serveris standartuli rolebia: sysadmin - asrulebs nebismier moqmedebas konkretul serverze; securityadmin - martavs momxmarebelta identi-fikatorebs, qmnis mb-s, kitxulobs Jurnals; serveradmin - nisnavs serveris konfiguraciis parametrebs; setupadmin - qmnis replikaciis obieqtebs da martavs gafartoebul procedurebs; processadmin - martavs procesebs SQL Server-is CarCoebSi; diskadmin - martavs mb-s failebs; dbcreator - qmnis da axdens mb-s modifikacias. 7. Database Access CanarTSi vircevt mb-s, agretve standartul rolebs mb-s doneze: db_owner - nebismieri rolis mqone wevrebisatvis nebadartuli moqmedebebis Sesruleba; db_accessadmin - momxmarebelta ricxvis damateba; db_datareader - nebismieri momxmareblis cxrilidan informaciis amoreba; db_datawriter -nebismieri momxmareblis cxrilsi monacemta damateba, ganaxleba da wasla; db_dlladmin - monacemta bazasi obieqtta damateba, ganaxleba da amogdeba; db_securityadmin - rolebisa da uflebebis martva; db_backupoperaror - monacemta bazis rezervirebis operaciebis Sesruleba; db_denydatareader - monacemta bazis sqemis modifi-cireba informaciis wakitxvis garese; db_denydatawriter - monacemta bazasi informaciis modificirebis akrzalva. garda ganxiluli `standartuli~ xerxisa momxmareblis identifikatori iqmneba ostatis gamoyenebitac: 181

182 1. gavusvat SQL Server Enterprise Manager, gavusvat ostati Create Login Wizard. Ok; 2. fanjarasi vircevt vin Seamowmebs momxmareblis identifikators: Windows NT Tu SQL Server; 3. Semdeg fanjarasi segvaqvs momxmareblis identifikatori da paroli. Semdeg vadasturebt parols. 4. momdeno fanjarasi vircevt momxmareblisatvis rols; 5. mietiteba mb, romeltanac mimartva nebadartulia;; 6. Finish. roli aris dasaxelebul uflebata krebuli serveris an konkretuli mb-s CarCoebSi. roli Public mb-s doneze miekutvneba yvela daregistrirebul momxmarebels am monacemta bazasi. rolis Seqmna-damateba mb-stan: 1. SQL Server Enterprise - is gaaqtiureba; gavxsnat monacemta baza serveris xesi; 2. marjvena Click, Database Roles saqaraldeze, konteqstur meniusi vircevt New database Role brzanebas; 3. fanjarasi Database Role Properties - New Role vircevt rolis tips: - momxmareblis rolebi (Standard Role) - danartis rolebi (Application Role) 4. pirveli tipis SemTxvevaSi gvicndeba mimartva User siastan da Add da Remove RilakebTan. Tu vawert Add-s gaixsneba Add Role Members fanjara, sadac warmodgenilia momxmareblebi. Tu vawert remove-s xdeba mocemuli rolidan momxmareblis amogdeba; 5. Ok. rolis amogdeba:l 1. marjvena Click rolze; 2. konteqstur meniusi vircevt Delete brzanebas. Yes. Tu rolze miwerilia Tundac erti momxmarebeli misi amogdeba ar SeiZleba. yvela roli ar eqvemdebareba amogdebas. (magalitad: Public an db_avner). mimartvis ufleba (permissions): 182

183 mimartvis uflebebis martvisatvis Transact SQL - Seicavs instruqciebs: GRANT - uflebebis miniweba; DENY - uflebebis CamorTmeva; REVOKE - adre miniwebul uflebata CamorTmeva. usafrtxoebis gaumjobesebisatvis gamoiyeneba agretve: warmodgenebi; obieqtebis an saqmiani procesebis (wesebis) gaucinareba; usafrtxoebis sistemis menejeri (System Security officer, SSO); fizikuri usafrtxoebis uzrunvelyofa. laboratoriuli samusao #14 SQL server - is usafrtxoebis sistema monacemta Sida da gare dacva monacemta bazis administratoris erterti ZiriTadi funqciaa. klient/serveris sistemasi usafrtxoeba realizdeba sami xerxit: - standartuli usafrtxoeba. am SemTxvevaSi SQL Server - ze sruldeba momxmareblis autentifikacia da sistemasi Sesvlaze SezRudvebis dadeba; - integrirebuli usafrtxoeba. am rejimsi musaobisas momxmareblis mimartvis sakitxebs wyvets Windows NT da usafrtxoeba xorcieldeba mimartvis kontrolis siis (Access Control List, ACL) daxmarebit. - Sereuli usafrtxoeba. igi warmoadgens standartuli da integrirebuli usafrtxoebis kombinacias. SQL Server-Si momxmareblis servertan mierteba xorcieldeba ori variantit: * Use Windows NT authentication - mierteba Windows NT momxmareblis saxelit; * Use SQL Server authentication - mierteba SQL Server-is saxelit. SQL Server-s gaacnia momxmareblis biujetis ori done: 183

184 I. momxmareblis identifikatori (Login) anu sistemasi Sesvla. sistemasi yvela Sesasvleli inaxeba mtavari monacemta bazis Master cxrilsi SYSLOGINS. II. TviTon `momxmarebeli~ (users) anu obieqtebi, romelta daxmarebit SQL Server mimartvis uflebebs martavs. yvela daregistrirebuli obieqti-momxmarebeli inaxeba yoveli monacemta bazis cxrilsi SYSUSERS, romeltac gaacniat mimartvis ufleba. SQL Server - Si arsebobs ori standartuli identifikatori: SA da BUILTIN / Administrators. SA miewereba rols sysadmin da gaacnia absoluturi uflebebi. BUILTIN / Administrators uzrunvelyofs serverisadmi mimartvas Windows NT administratuli jgufis yvela wevrisatvis. momxmareblis identifikatoris Sesaqmnelad sawiroa: 1. SQL Server Enterprise Manager-is gaaqtiureba; 2. vircevt servers; 3. marjvena Click, Logins saqaraldeze da konteqstur meniusi vircevt New Login; 4. General CanarTSi: Segvyavs momxmareblis identifikatori, vircevt enas da mb-s; 5. Tu vircevt gadamrtvels Windows NT Authentication da domens siasi Domain, masin SQL Server operaciul sistemasi momxmareblis Sesvlis Semdeg damatebit Semowmebas arar Caatarebs. (Grant Access - nebadartulia, Deny Access - akrzalulia). Tu vircevt gadamrtvels SQL Server Authentication, masin sistema aketebs Semowmebas; 6. Server Roles CanarTSi TiToeuli momxmarebli-satvis ganvsazrvravt uflebebs. serveris standartuli rolebia: sysadmin - asrulebs nebismier moqmedebas konkretul serverze; securityadmin - martavs momxmarebelta identi-fikatorebs, qmnis mb-s, kitxulobs Jurnals; serveradmin - nisnavs serveris konfiguraciis parametrebs; setupadmin - qmnis replikaciis obieqtebs da martavs gafartoebul procedurebs; processadmin - martavs procesebs SQL Server-is CarCoebSi; diskadmin - martavs mb-s failebs; dbcreator - qmnis da axdens mb-s modifikacias. 7. Database Access CanarTSi vircevt mb-s, agretve standartul rolebs mb-s doneze: 184

185 db_owner - nebismieri rolis mqone wevrebisatvis nebadartuli moqmedebebis Sesruleba; db_accessadmin - momxmarebelta ricxvis damateba; db_datareader - nebismieri momxmareblis cxrilidan informaciis amoreba; db_datawriter -nebismieri momxmareblis cxrilsi monacemta damateba, ganaxleba da wasla; db_dlladmin - monacemta bazasi obieqtta damateba, ganaxleba da amogdeba; db_securityadmin - rolebisa da uflebebis martva; db_backupoperaror - monacemta bazis rezervirebis operaciebis Sesruleba; db_denydatareader - monacemta bazis sqemis modifi-cireba informaciis wakitxvis garese; db_denydatawriter - monacemta bazasi informaciis modificirebis akrzalva. garda ganxiluli `standartuli~ xerxisa momxmareblis identifikatori iqmneba ostatis gamoyenebitac: 2. gavusvat SQL Server Enterprise Manager, gavusvat ostati Create Login Wizard. Ok; 2. fanjarasi vircevt vin Seamowmebs momxmareblis identifikators: Windows NT Tu SQL Server; 3. Semdeg fanjarasi segvaqvs momxmareblis identifikatori da paroli. Semdeg vadasturebt parols. 4. momdeno fanjarasi vircevt momxmareblisatvis rols; 5. mietiteba mb, romeltanac mimartva nebadartulia;; 6. Finish. roli aris dasaxelebul uflebata krebuli serveris an konkretuli mb-s CarCoebSi. roli Public mb-s doneze miekutvneba yvela daregistrirebul momxmarebels am monacemta bazasi. rolis Seqmna-damateba mb-stan: 1. SQL Server Enterprise - is gaaqtiureba; gavxsnat monacemta baza serveris xesi; 185

186 2. marjvena Click, Database Roles saqaraldeze, konteqstur meniusi vircevt New database Role brzanebas; 3. fanjarasi Database Role Properties - New Role vircevt rolis tips: - momxmareblis rolebi (Standard Role) - danartis rolebi (Application Role) 4. pirveli tipis SemTxvevaSi gvicndeba mimartva User siastan da Add da Remove RilakebTan. Tu vawert Add-s gaixsneba Add Role Members fanjara, sadac warmodgenilia momxmareblebi. Tu vawert remove-s xdeba mocemuli rolidan momxmareblis amogdeba; 5. Ok. rolis amogdeba:l 1. marjvena Click rolze; 2. konteqstur meniusi vircevt Delete brzanebas. Yes. Tu rolze miwerilia Tundac erti momxmarebeli misi amogdeba ar SeiZleba. yvela roli ar eqvemdebareba amogdebas. (magalitad: Public an db_avner). mimartvis ufleba (permissions): mimartvis uflebebis martvisatvis Transact SQL - Seicavs instruqciebs: GRANT - uflebebis miniweba; DENY - uflebebis CamorTmeva; REVOKE - adre miniwebul uflebata CamorTmeva. usafrtxoebis gaumjobesebisatvis gamoiyeneba agretve: warmodgenebi; obieqtebis an saqmiani procesebis (wesebis) gaucinareba; usafrtxoebis sistemis menejeri (System Security officer, SSO); fizikuri usafrtxoebis uzrunvelyofa. 186

187 replikacia (Replication) replikaciebi SQL Server-Si serverebs Soris informaciis dublirebis sasualebas izleva. replikaciis modelsi arsebobs sami sxvadasxva gasareburi donis komponentebi: xelmomweri (Subscriber), gamomcemeli (Publisher) da gamanawilebeli (Distributor). musaobis dawyebamde unda Semowmdes sawiro servertan SeerTeba, rac PING utilitis mesveobit testirdeba: ODBCPING [-s serveris-saxeli] [-d DSN] [-u momxmareblis-saxeli] [-p paroli] dadebiti Setyobinebis mirebis Semdeg unda gadawydes replikaciis varianti: _ mteli monacemta baza (entire database) _ mteli cxrilebi (entire tables) _ informaciis horizontaluri nawilebi horizontal partitions) _ informaciis vertikaluri nawilebi (vertical partitions) _ SerCeviTi warmodgenebi (custom views) 187

188 laboratoriuli samusao #15 musaoba SQL Enterprise Manager-Si : axali publikaciis Seqmna 1) publikaciis dayenebis pirvel bijs warmoadgens Enterprise Manager-Si dasorebuli serveris registracia. axali publikaciis Seqmnis ori gza arsebobs: sistemuri Sesanaxi procedurebis an publikaciic Seqmnis ostati (Create Publication Wizard). 2) ostatis gamoyenebis SemTxvevaSi mnisvneloba aqvs aris Tu ara ukve Tundac erti publikacia. * Tu pasuxi dadebitia, masin ostats SeuZlia misi Sablonad gamoyeneba; * Tu es pirveli publikaciaa, masin ostati dainteresdeba serverit, romelzec monacemta baza gantavsdeba. arsebobs ori varianti: Register Server No, use another server; 3) Semdeg unda gadawydes (mietitos) replikaciis tipi: Snapshot publication Transaction publication Merge publication; 4) Semdeg wydeba xelmomwerta Semadgenlobis sakitxi: 5) momdevno fanjarasi ganisazrvreba publikaciis Semadgenloba-cxrilebis krebuli; 6) Options for Articles fanjris General CanarTSi ganisazrvreba statiis parametrebi; Snapshot CanarTSi mietiteba sinqronizaciis parametrebi; Resolver CanarTSi ganisazrvreba, Tu rogor gadawydeba konfliqti; 7) Semdeg publikacias eniweba saxeli, mokle arwera, qseluri grafikis SemcirebisaTvis SeiZleba daematos filtri. da a.s. Internet-Si mb-ebis musaobis dros SeiZleba: gaixsnas mimartva anonimuri xelmomwerebisatvis (anonimous subscriber) an ufro mkacri dacvis organizeba moxdes, roca mxolod registrirebul xelmomwerebs (enabled subscriber) ezlevat mb-stan mimartva; 188

189 8) ostatis bolo fanjarasi moicema arceul parametrebis arwera da mati Secvlis SesaZlebloba; mimreb serverze xelmoweris dayenebisatvis igive bijebi unda gaketdes. ertaderti gansxvaveba mdgomareobs imasi, rom replikaciis processi Cans ara gadamcemi, aramed mimrebi serveri. xelmoweris inicializaciisatvis: 1.SQL Server Enterprise Manager-is meniudan an konteqsturi meniudan vircevt Tools / Replication / Create and manage publication; 2. Semdeg fanjarasi vawert Push New Subscription Rilaks; 3. ostati miaertebs mocemuli momentisatvis SerCeul publikacias, ristvisac sawiroa mb-s mititeba, sadac gadaicema cvlilebebi; 4. ostati itxovs ganawilebis agentis musaobis grafiks. ramdenime SekiTxvis semdeg gamodis fanjara SerCeuli parametrebis CamonaTvliT; 5. Finish. cxrilebis importi Data Transformation Servece - is daxmarebit. 1. vircevt mb-s. Click, Run a Wizard Rilakze (jadosnuri joxi gamosaxulebit) an Help / Wizard; 2. Shoose a Data Source fanjarasi vircevt Microsoft Access striqons, Click, File Builder Rilakze (mravalwertilis gamosaxulebit). Open fanjarasi, Double Click failze. mdb, User Name-Si Admin. Click Rilakze Advanced specifiuri Tvisebebis misatiteblad monacemta wyarosatvis. Next. 3. Shoose a Destination fanjarasi Next; 4. Specify Table Copy or Query fanjarasi, Source Database velsi visargeblot Copy Table(s) da Next. 5. Select Source Tables fanjarasi, Click, Select All Rilakze. movxsnat drosa cxrilebs, romlebic daemata fails. mdb da SevcvaloT failis saxeli dbo.[order Details] saxelit dbo.[order_details]; 6. Click Rilakze Transform builder (mravalwertiliani gamosaxulebit) cxrilis Categories striqonsi. Column Mappings CanarTSi aisaxeba monacemta velebis tipebi; 7. Transformation CanarTSi vircevt Transformation information as it is copied to the destination opcias; 189

190 8. Cancel. Next. 9. Save and Schedule Package fanjarasi Next; 10. Finish. Ok. 11. Double click, Tables saqaraldeze. replikaciis konfiguracia Wizard-ebis gamoyenebit SQL Server-Si replikaciis konfigurirebisatvis gamoiyeneba rogorc Sesanaxi procedurebi, ise Configure Publishing And Distribution Wizard, Tumca Enterprise Manager-is mesveobit gamoiyeneba agretve replikaciis konfigurirebis sxva Wizard-ebic: Create Publication Wizard. Create Pull Subscription Wizard. Create Push Subscription Wizard. Disable Publishing And Distribution Wizard. publikaciisa da gavrcelebis konfigurirebisatvis sruldeba Semdegi bijebi: 1. Enterprise Manager-is fanjarasi Click serverze. Tools meniudan vircevt punqts Wizards. fanjarasi Select Wizard vxsnit saqaraldes Replication da vircevt Configure Publishing and Distribution Wizard. Click Rilakze OK. nax fanjara Select Wizard 190

191 2. Cndeba fanjara Configure Publishing and Distribution Wizard (nax ). nax fanjara Configure Publishing and Distribution Wizard 3. Click Rilakze Next. Cndeba fanjara Select Distributor (nax ), sadac SegviZlia 1-el bijze arceuli serveri gavxadot rogorc distributori, ise gamomcemeli. mocemul magalitsi ganixileba distributoris varianti. fanjarasi Registered SQL Server Properties Click Rilakze Add Server. vircevt autentifikaciis metods. nax fanjara Select Distributor 191

192 4. mocemul bijze Wizard amowmebs SeuZlia Tu ara gamomcemels mimartos distributors. mimartvis arqonis SemTxvevaSi xdeba SQL Server Agent Properties fanjris gamozaxeba (nax ), sadac SesaZlebelia agentis sxva Tvisebebis modificirebac. bolos, Click Rilakze OK. nax fanjara SQL Server Agent Properties 5. Cndeba fanjara Configure SQL Server Agent (nax ), sadac agentis avtomatur rejimsi konfigurirebis piroba unda gadawydes. Click Rilakze Next. nax fanjara Configure SQL Server Agent 192

193 6. Cndeba fanjara Specify Snaphot Folder (nax ), sadac moicema suratis gantavsebis adgili. Click Rilakze Next. nax fanjara Specify Snaphot Folder 7. Cndeba fanjara Customize the Configuration (nax ), sadac SeiZleba ucvlelad davtovot parametrebi distribuciis monacemta bazisatvis (meore Rilaki) an mistvis avirciot awyobis varianti (pirveli Rilaki). mocemuli magalitisatvis vircevt pirvel Rilaks. nax fanjara Customize the Configuration 193

194 8. Click Rilakze Next. Cndeba fanjara Provide Distribution Database Information, sadac vizlevit distribuciuli bazis saxelsa da adgilsamyofels (nax ). nax fanjara Provide Distribution Database Information 9. Click Rilakze Next. Cndeba fanjara Enable Publishers (nax ), sadac SesaZlebelia an 1-el bijze ukve arceuli serverisagan dansxvavebuli gamomcemlis gamoyeneba an gamomcemlis damateba. nax fanjara Enable Publishers 194

195 10. Click Rilakze Next. Cndeba fanjara Enable Publication Databases (nax ). aq SesaZlebelia replikaciis aqtivizeba. nax fanjara Enable Publication Databases 11. Click Rilakze Next. Cndeba fanjara Enable Subscribers (nax ), sadac SesaZlebelia xelmomweris SerCeva ukve SerCeuli gamomcemlis mixedvit, mizansewonilia gaketdes Configure Publishing and Distribution Wizard. nax fanjara Enable Subscribers 195

196 12. Click Rilakze Next. Cndeba fanjara Completing the Configure Publishing and Distribution Wizard (nax ), sadac nacvenebia Cveni parametrebis Sesaxeb monacemebi. Click Rilakze Finish. replikaciis agentebis SesrulebisaTvis sawiroa SQL Server Agent gasveba, romlis damtavrebis Semdeg Enterprise Manager fanjarasi gamocndeba saqaralde Replication Monitor. nax publikaciis konfigurireba. publikaciis konfigurirebisatvis sruldeba Semdegi bijebi: 1. Enterprise Manager-is fanjarasi Click serverze. Tools meniudan vircevt punqts Wizards. fanjarasi Select Wizard vxsnit saqaraldes Replication da vircevt Create Publication Wizard. Cndeba dialoguri fanjara Create and Manage Publications, sadac vircevt monacemta bazas an cxrils, romlis publikaciac gvinda (nax ). nax fanjara Create and Manage Publications 196

197 2. vircevt monacemta bazas ( Northwind), Semdeg Click Rilakze Create Publication. Cndeba fanjara Create Publication Wizard (nax ). yuradreba mivaqciot drosas Show advanced options in this wizard. nax fanjara Create Publication Wizard 3. Click Rilakze Next. Cndeba fanjara Choose Publication Database (nax ), sadac SesaZlebelia monacemta bazis xelaxla SerCeva. nax fanjara Choose Publication Database 197

198 4. Click Rilakze Next. Cndeba fanjara Select Publication Type (nax ). vircevt replikaciis tips. nax fanjara Select Publication Type Cvens SemTxvevaSi vircevt Snapshot Publication. gadavdivart Specify Subscriber Types fanjaraze. vircevt xelmomwerta tips da Click Rilakze Next. nax fanjara Specify Subscriber Types 198

199 5. fanjarasi Specify Articles mivutitebt cxrilebs an sxva obieqtebs, romlebic statiis saxit iqnebian replicirebuli (nax ). nax fanjara Specify Articles 6. statiis Tvisebebis SerCevis Semdeg gamovdivart fanjridan Specify Articles da garkveuli manipulaciebis Semdeg gadavdivart Select Publication Name and Description fanjarasi (nax ), sadac vircevt publikaciis saxelsa da arweras. nax fanjara Select Publication Name and Description 199

inga abulaze laboratoriuli samusaoebi VBA enaze `teqnikuri

inga abulaze laboratoriuli samusaoebi VBA enaze `teqnikuri inga abulaze laboratoriuli samusaoebi VBA enaze `teqnikuri universiteti @ saqartvelos teqnikuri universiteti inga abulaze laboratoriuli samusaoebi VBA enaze registrirebulia stu-s saredaqcio-sagamomcemlo

More information

saqartvelos teqnikuri universiteti

saqartvelos teqnikuri universiteti saqartvelos teqnikuri universiteti g. janelize daprogramebis safuzvlebi damtkicebulia stu-s saswavlo-metoduri sabwos mier Tbilisi 2002 uak 681.3.06 wignsi ganxilulia daprogrameba Turbo Pascal-is, Object

More information

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL HOW TO CREATE AND MAINTAIN DATABASES AND TABLES By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate

More information

obieqtze orientirebuli programirebis ena C#

obieqtze orientirebuli programirebis ena C# T. baxtaze obieqtze orientirebuli programirebis ena C# Object Main Class { this new new this Object new Object this "teqnikuri universiteti" saqartvelos teqnikuri universiteti T. baxtaze obieqtze orientirebuli

More information

დისკრეტული სტრუქტურების გაფართოვება: პროგრამული ენა ჰასკელი

დისკრეტული სტრუქტურების გაფართოვება: პროგრამული ენა ჰასკელი Tbilisis saxelmwifo universiteti zusti da sabunebismetyvelo mecnierebata fakulteti ინტერდისციპლინური (მათემატიკა, კომპიუტერული მეცნიერებები) ქვემიმართულება: მათემატიკური ლოგიკა და დისკრეტული სტრუქტურები

More information

maswavlebelta profesiuli ganvitarebis centri informaciulsakomunikacio teqnologiebis sabazo kursi maswavleblebistvis maswavlebelta informaciul-sakomunikacio teqnologiebis treningis programa maswavlebelta

More information

Lab 4: Tables and Constraints

Lab 4: Tables and Constraints Lab : Tables and Constraints Objective You have had a brief introduction to tables and how to create them, but we want to have a more in-depth look at what goes into creating a table, making good choices

More information

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 1. Introduction to SQL Server Panayiotis Andreou Department of Computer Science University of Cyprus EPL342 Databases Lab 1 Introduction to SQL Server 2008 Panayiotis Andreou http://www.cs.ucy.ac.cy/courses/epl342 1-1 Before We Begin Start the SQL Server

More information

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types Dr. Shohreh Ajoudanian Course Topics Microsoft SQL Server 01 Installing MSSQL Server 2008 03 Creating a database 05 Querying Tables with SELECT 07 Using Set Operators 02 Data types 04 Creating a table,

More information

This course is aimed at those who need to extract information from a relational database system.

This course is aimed at those who need to extract information from a relational database system. (SQL) SQL Server Database Querying Course Description: This course is aimed at those who need to extract information from a relational database system. Although it provides an overview of relational database

More information

II. grafika. grafikuli obieqtebis ageba: funqcia Graphics

II. grafika. grafikuli obieqtebis ageba: funqcia Graphics II. grafika grafikuli obieqtebis ageba: fuqcia Graphics wia leqciasi Cve gavixilet Mathematica sistemis grafikuli fuqciebi Plot (grafikis ageba sibrtkeze) da Plot3D (grafikis ageba sivrcesi). agretve gaxiluli

More information

Lab # 4. Data Definition Language (DDL)

Lab # 4. Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Lab # 4 Data Definition Language (DDL) Eng. Haneen El-Masry November, 2014 2 Objective To be familiar with

More information

Exact Numeric Data Types

Exact Numeric Data Types SQL Server Notes for FYP SQL data type is an attribute that specifies type of data of any object. Each column, variable and expression has related data type in SQL. You would use these data types while

More information

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2

Constraints. Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers. John Edgar 2 CMPT 354 Constraints Primary Key Foreign Key General table constraints Domain constraints Assertions Triggers John Edgar 2 firstname type balance city customerid lastname accnumber rate branchname phone

More information

Transact-SQL Techniques

Transact-SQL Techniques Transact-SQL Techniques Transact-SQL, an extension to the SQL database programming language, is a powerful language offering many features. Transact-SQL provides the SQL Server developer with several useful

More information

Senturus Analytics Connector. User Guide Cognos to Power BI Senturus, Inc. Page 1

Senturus Analytics Connector. User Guide Cognos to Power BI Senturus, Inc. Page 1 Senturus Analytics Connector User Guide Cognos to Power BI 2019-2019 Senturus, Inc. Page 1 Overview This guide describes how the Senturus Analytics Connector is used from Power BI after it has been configured.

More information

Data Definition Language (DDL)

Data Definition Language (DDL) Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Database Lab (ECOM 4113) Lab 6 Data Definition Language (DDL) Eng. Mohammed Alokshiya November 11, 2014 Database Keys A key

More information

My Company Tel: Fax: SQLserverPrint

My Company Tel: Fax: SQLserverPrint My Company Tel: +44 1234 567 9898 Fax: +44 1234 545 9999 email: info@@company.com SQL Server Database Schema Document Created using SQLserverPrint Macro Variables Substitution Example General Date 14/01/2017

More information

GridDB Advanced Edition SQL reference

GridDB Advanced Edition SQL reference GMA022C1 GridDB Advanced Edition SQL reference Toshiba Solutions Corporation 2016 All Rights Reserved. Introduction This manual describes how to write a SQL command in the GridDB Advanced Edition. Please

More information

Code Centric: T-SQL Programming with Stored Procedures and Triggers

Code Centric: T-SQL Programming with Stored Procedures and Triggers Apress Books for Professionals by Professionals Sample Chapter: "Data Types" Code Centric: T-SQL Programming with Stored Procedures and Triggers by Garth Wells ISBN # 1-893115-83-6 Copyright 2000 Garth

More information

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2

Department of Computer Science University of Cyprus. EPL342 Databases. Lab 2 Department of Computer Science University of Cyprus EPL342 Databases Lab 2 ER Modeling (Entities) in DDS Lite & Conceptual Modeling in SQL Server 2008 Panayiotis Andreou http://www.cs.ucy.ac.cy/courses/epl342

More information

CMP-3440 Database Systems

CMP-3440 Database Systems CMP-3440 Database Systems Relational DB Languages SQL Lecture 06 zain 1 Purpose and Importance Database Language: To create the database and relation structures. To perform various operations. To handle

More information

Creating and Configuring Databases

Creating and Configuring Databases 3 Creating and Configuring Databases This chapter begins by examining SQL Server database storage concepts and database sizing considerations. We will also review how to create, change, and configure a

More information

Senturus Analytics Connector. User Guide Cognos to Tableau Senturus, Inc. Page 1

Senturus Analytics Connector. User Guide Cognos to Tableau Senturus, Inc. Page 1 Senturus Analytics Connector User Guide Cognos to Tableau 2019-2019 Senturus, Inc. Page 1 Overview This guide describes how the Senturus Analytics Connector is used from Tableau after it has been configured.

More information

Insert Into Customer1 (ID, CustomerName, City, Country) Values(103, 'Marwa','Baghdad','Iraq')

Insert Into Customer1 (ID, CustomerName, City, Country) Values(103, 'Marwa','Baghdad','Iraq') Insert Into Customer1 (ID, CustomerName, City, Country) Values(103, 'Marwa','Baghdad','Iraq') Notes: 1. To View the list of all databases use the following command: Select * (or name) From Sys.databases

More information

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama The Islamic University of Gaza Faculty of Engineering Department of Computer Engineering ECOM 4113: Database Lab Lab # 2 Data Definition Language (DDL) Eng. Alaa O Shama October, 2015 Objective To be familiar

More information

Data Definition Language

Data Definition Language Chapter 5 Data Definition Language In This Chapter c Creating Database Objects c Modifying Database Objects c Removing Database Objects 96 Microsoft SQL Server 2012: A Beginner s Guide This chapter describes

More information

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1 SQL Fundamentals Chapter 3 Class 03: SQL Fundamentals 1 Class 03: SQL Fundamentals 2 SQL SQL (Structured Query Language): A language that is used in relational databases to build and query tables. Earlier

More information

Installation and Configuration Guide

Installation and Configuration Guide Senturus Analytics Connector Version 2.2 Installation and Configuration Guide Senturus Inc. 533 Airport Blvd. Suite 400 Burlingame CA 94010 P 888 601 6010 F 650 745 0640 2017 Senturus, Inc. Table of Contents

More information

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language

Information Systems Engineering. SQL Structured Query Language DDL Data Definition (sub)language Information Systems Engineering SQL Structured Query Language DDL Data Definition (sub)language 1 SQL Standard Language for the Definition, Querying and Manipulation of Relational Databases on DBMSs Its

More information

System Pages (Setup Admins Only)

System Pages (Setup Admins Only) System Pages (Setup Admins Only) 1 Primary System Pages 2 More on Page Views & Sub Page Views 3 4 System Lookup Pages 5 6 7 Distinguishing Tables, Pages, Filtered Pages, & Page Views 8 9 Reasons to Create

More information

SQL Data Definition and Data Manipulation Languages (DDL and DML)

SQL Data Definition and Data Manipulation Languages (DDL and DML) .. Cal Poly CPE/CSC 365: Introduction to Database Systems Alexander Dekhtyar.. SQL Data Definition and Data Manipulation Languages (DDL and DML) Note: This handout instroduces both the ANSI SQL synatax

More information

Installation and Configuration Guide

Installation and Configuration Guide Senturus Analytics Connector Version 2.2 Installation and Configuration Guide Senturus Inc 533 Airport Blvd. Suite 400 Burlingame CA 94010 P 888 601 6010 F 650 745 0640 Table of Contents 1. Install Senturus

More information

EXAMINATIONS 2009 END-YEAR. COMP302 / SWEN304 Database Systems / Database System Engineering. Appendix

EXAMINATIONS 2009 END-YEAR. COMP302 / SWEN304 Database Systems / Database System Engineering. Appendix EXAMINATIONS 2009 END-YEAR COMP302 / SWEN304 Database Systems / Database System Engineering Appendix Do not hand this Appendix in. Do not write your answers on this Appendix. Contents: Appendix A. COMPANY

More information

Basis Data Terapan. Yoannita

Basis Data Terapan. Yoannita Basis Data Terapan Yoannita SQL Server Data Types Character strings: Data type Description Storage char(n) varchar(n) varchar(max) text Fixed-length character string. Maximum 8,000 characters Variable-length

More information

DB2 Function Conversion for Sybase ASE Users

DB2 Function Conversion for Sybase ASE Users DB2 Function Conversion for Sybase ASE Users ChangSung KANG, Kitty Lau IMTE Version 1.2 Date: July-01-2011 Page:1 Version: 1.1 Document History Version Date Author Comment Authorization 1.0 07/01/2011

More information

/* --6). Name: Christopher Singleton Date: 02/12/2017 Class: PROG 140 Project: Module 04

/* --6). Name: Christopher Singleton Date: 02/12/2017 Class: PROG 140 Project: Module 04 /* --6. Name: Christopher Singleton Date: 02/12/2017 Class: PROG 140 Project: Module 04 About this Original Script: Drops Database IF EXISTS / Creates Database / Inserts three rows into three tables with

More information

Microsoft SQL Server - Concepts 2 005

Microsoft SQL Server - Concepts 2 005 1 Taught by: Aiman Mobarak Elkhalifa SQL Server Overview SQL Server 2 Overview 2 Taught by: Aiman Mobarak Elkhalifa Microsoft SQL Server 2 is a database platform for large-scale Online Transaction Processing

More information

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior

SQL. Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior SQL Rodrigo García Carmona Universidad San Pablo-CEU Escuela Politécnica Superior 1 DDL 2 DATA TYPES All columns must have a data type. The most common data types in SQL are: Alphanumeric: Fixed length:

More information

Structured Query Language (SQL)

Structured Query Language (SQL) Structured Query Language (SQL) SQL Chapters 6 & 7 (7 th edition) Chapters 4 & 5 (6 th edition) PostgreSQL on acsmysql1.acs.uwinnipeg.ca Each student has a userid and initial password acs!

More information

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved. Database Foundations 6-3 Roadmap You are here Introduction to Oracle Application Express Structured Query Language (SQL) Data Definition Language (DDL) Data Manipulation Language (DML) Transaction Control

More information

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement

Chapter 4. Basic SQL. SQL Data Definition and Data Types. Basic SQL. SQL language SQL. Terminology: CREATE statement Chapter 4 Basic SQL Basic SQL SQL language Considered one of the major reasons for the commercial success of relational databases SQL Structured Query Language Statements for data definitions, queries,

More information

Chapter-14 SQL COMMANDS

Chapter-14 SQL COMMANDS Chapter-14 SQL COMMANDS What is SQL? Structured Query Language and it helps to make practice on SQL commands which provides immediate results. SQL is Structured Query Language, which is a computer language

More information

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011 Introduction to SQL IT 5101 Introduction to Database Systems J.G. Zheng Fall 2011 Overview Using Structured Query Language (SQL) to get the data you want from relational databases Learning basic syntax

More information

Symptom. Environment. Resolution What words are reserved and cannot be used in BPC? Version 3 Validity:

Symptom. Environment. Resolution What words are reserved and cannot be used in BPC? Version 3 Validity: SAP Knowledge Base Article 1632682 - What words are reserved and cannot be used in BPC? Version 3 Validity: 16.09.2011 - active Language English Symptom What words are reserved and cannot be used in Business

More information

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Basic SQL Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 4 Outline SQL Data Definition and Data Types Specifying Constraints in SQL Basic Retrieval Queries

More information

Database and table creation

Database and table creation Database and table creation Introduction SQL - Structured Query Language used to create, modify databases, and to place and retrieve data from databases. SQL was developed in the 70s at IBM. It has become

More information

Activant Solutions Inc. SQL 2005: Basic Data Manipulation

Activant Solutions Inc. SQL 2005: Basic Data Manipulation Activant Solutions Inc. SQL 2005: Basic Data Manipulation SQL Server 2005 suite Course 4 of 4 This class is designed for Beginner/Intermediate SQL Server 2005 System Administrators Objectives System Stored

More information

Principles of Data Management

Principles of Data Management Principles of Data Management Alvin Lin August 2018 - December 2018 Structured Query Language Structured Query Language (SQL) was created at IBM in the 80s: SQL-86 (first standard) SQL-89 SQL-92 (what

More information

Compression Users Guide. Adaptive Server Enterprise 15.7

Compression Users Guide. Adaptive Server Enterprise 15.7 Compression Users Guide Adaptive Server Enterprise 15.7 DOCUMENT ID: DC01667-01-1570-01 LAST REVISED: September 2011 Copyright 2011 by Sybase, Inc. All rights reserved. This publication pertains to Sybase

More information

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture

COGS 121 HCI Programming Studio. Week 03 - Tech Lecture COGS 121 HCI Programming Studio Week 03 - Tech Lecture Housekeeping Assignment #1 extended to Monday night 11:59pm Assignment #2 to be released on Tuesday during lecture Database Management Systems and

More information

SQL Structured Query Language (1/2)

SQL Structured Query Language (1/2) Oracle Tutorials SQL Structured Query Language (1/2) Giacomo Govi IT/ADC Overview Goal: Learn the basic for interacting with a RDBMS Outline SQL generalities Available statements Restricting, Sorting and

More information

After completing this unit, you should be able to: Define the terms

After completing this unit, you should be able to: Define the terms Introduction Copyright IBM Corporation 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM. 4.0.3 3.3.1 Unit Objectives After completing this unit,

More information

@vmahawar. Agenda Topics Quiz Useful Links

@vmahawar. Agenda Topics Quiz Useful Links @vmahawar Agenda Topics Quiz Useful Links Agenda Introduction Stakeholders, data classification, Rows/Columns DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE CONSTRAINTS, DATA TYPES DML Data

More information

COPYRIGHTED MATERIAL. Contents. Chapter 1: Introducing T-SQL and Data Management Systems 1. Chapter 2: SQL Server Fundamentals 23.

COPYRIGHTED MATERIAL. Contents. Chapter 1: Introducing T-SQL and Data Management Systems 1. Chapter 2: SQL Server Fundamentals 23. Introduction Chapter 1: Introducing T-SQL and Data Management Systems 1 T-SQL Language 1 Programming Language or Query Language? 2 What s New in SQL Server 2008 3 Database Management Systems 4 SQL Server

More information

Every Byte Counts. Why Datatype Choices Matter. Andy Yun, Database Architect/Developer

Every Byte Counts. Why Datatype Choices Matter. Andy Yun, Database Architect/Developer Every Byte Counts Why Datatype Choices Matter Andy Yun, Database Architect/Developer Thank You Presenting Sponsors Gain insights through familiar tools while balancing monitoring and managing user created

More information

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC

BEGINNING T-SQL. Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC BEGINNING T-SQL Jen McCown MidnightSQL Consulting, LLC MinionWare, LLC FIRST: GET READY 1. What to model? 2. What is T-SQL? 3. Books Online (BOL) 4. Transactions WHAT TO MODEL? What kind of data should

More information

SQL Server Administration Class 4 of 4. Activant Prophet 21. Basic Data Manipulation

SQL Server Administration Class 4 of 4. Activant Prophet 21. Basic Data Manipulation SQL Server Administration Class 4 of 4 Activant Prophet 21 Basic Data Manipulation This class is designed for Beginner SQL/Prophet21 users who are responsible for SQL Administration as it relates to Prophet

More information

SQL Commands & Mongo DB New Syllabus

SQL Commands & Mongo DB New Syllabus Chapter 15 : Computer Science Class XI ( As per CBSE Board) SQL Commands & Mongo DB New Syllabus 2018-19 SQL SQL is an acronym of Structured Query Language.It is a standard language developed and used

More information

T- SQL Lab Exercises and Examples

T- SQL Lab Exercises and Examples T- SQL Lab Exercises and Examples Table of Contents 1. T-SQL - OVERVIEW... 4 2. T-SQL SERVER - DATA TYPES... 5 3. T-SQL SERVER - CREATE TABLES... 8 4. T-SQL SERVER - DROP TABLES... 10 5. T-SQL SERVER -

More information

Mastering Transact-SQL An Overview of SQL Server 2000 p. 3 SQL Server's Networked Architecture p. 4 SQL Server's Basic Components p.

Mastering Transact-SQL An Overview of SQL Server 2000 p. 3 SQL Server's Networked Architecture p. 4 SQL Server's Basic Components p. Acknowledgments p. xxiii Introduction p. xxv Mastering Transact-SQL An Overview of SQL Server 2000 p. 3 SQL Server's Networked Architecture p. 4 SQL Server's Basic Components p. 8 Transact-SQL p. 9 SQL

More information

MTAT Introduction to Databases

MTAT Introduction to Databases MTAT.03.105 Introduction to Databases Lecture #3 Data Types, Default values, Constraints Ljubov Jaanuska (ljubov.jaanuska@ut.ee) Lecture 1. Summary SQL stands for Structured Query Language SQL is a standard

More information

Chapter - 1 INTRODUCTION TO DATABASES

Chapter - 1 INTRODUCTION TO DATABASES Chapter - 1 INTRODUCTION TO DATABASES A database is an integrated collection of inter-related data, stored with minimum redundancy and serves many users/application quickly and efficiency. A database system

More information

Compression Users Guide. SAP Adaptive Server Enterprise 16.0

Compression Users Guide. SAP Adaptive Server Enterprise 16.0 Compression Users Guide SAP Adaptive Server Enterprise 16.0 DOCUMENT ID: DC01667-01-1600-01 LAST REVISED: May 2014 Copyright 2014 by SAP AG or an SAP affiliate company. All rights reserved. No part of

More information

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables INDEX Exercise No Title 1 Basic SQL Statements 2 Restricting and Sorting Data 3 Single Row Functions 4 Displaying data from multiple tables 5 Creating and Managing Tables 6 Including Constraints 7 Manipulating

More information

Get Table Schema In Sql Server 2005 Modify. Column Datatype >>>CLICK HERE<<<

Get Table Schema In Sql Server 2005 Modify. Column Datatype >>>CLICK HERE<<< Get Table Schema In Sql Server 2005 Modify Column Datatype Applies To: SQL Server 2014, SQL Server 2016 Preview Specifies the properties of a column that are added to a table by using ALTER TABLE. Is the

More information

Appendix A. Using DML to Modify Data. Contents: Lesson 1: Adding Data to Tables A-3. Lesson 2: Modifying and Removing Data A-8

Appendix A. Using DML to Modify Data. Contents: Lesson 1: Adding Data to Tables A-3. Lesson 2: Modifying and Removing Data A-8 A-1 Appendix A Using DML to Modify Data Contents: Lesson 1: Adding Data to Tables A-3 Lesson 2: Modifying and Removing Data A-8 Lesson 3: Generating Numbers A-15 A-2 Using DML to Modify Data Module Overview

More information

Smart Database [Stored Procedures - Functions Trigger]

Smart Database [Stored Procedures - Functions Trigger] Smart Database [Stored Procedures - Functions Trigger] Stored Procedures A stored procedure is an already written SQL statement that is saved in the database. Benefits of Stored Procedures: 1. Precompiled

More information

IT360: Applied Database Systems. SQL: Structured Query Language DDL and DML (w/o SELECT) (Chapter 7 in Kroenke) SQL: Data Definition Language

IT360: Applied Database Systems. SQL: Structured Query Language DDL and DML (w/o SELECT) (Chapter 7 in Kroenke) SQL: Data Definition Language IT360: Applied Database Systems SQL: Structured Query Language DDL and DML (w/o SELECT) (Chapter 7 in Kroenke) 1 Goals SQL: Data Definition Language CREATE ALTER DROP SQL: Data Manipulation Language INSERT

More information

Senturus Analytics Connector Version 3.0. User Guide. Senturus, Inc. 533 Airport Blvd. Suite 400 Burlingame CA P F

Senturus Analytics Connector Version 3.0. User Guide. Senturus, Inc. 533 Airport Blvd. Suite 400 Burlingame CA P F Senturus Analytics Connector Version 3.0 User Guide Senturus, Inc. 533 Airport Blvd. Suite 400 Burlingame CA 94010 P 888 601 6010 F 650 745 0640 Table of Contents 1. Install and Configure Senturus Analytics

More information

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng.

Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng. Islamic University of Gaza Faculty of Engineering Department of Computer Engineering Fall 2011 ECOM 4113: Database System Lab Eng. Ahmed Abumarasa Database Lab Lab 2 Database Table Introduction: The previous

More information

Exam code: Exam name: Database Fundamentals. Version 16.0

Exam code: Exam name: Database Fundamentals. Version 16.0 98-364 Number: 98-364 Passing Score: 800 Time Limit: 120 min File Version: 16.0 Exam code: 98-364 Exam name: Database Fundamentals Version 16.0 98-364 QUESTION 1 You have a table that contains the following

More information

1) Introduction to SQL

1) Introduction to SQL 1) Introduction to SQL a) Database language enables users to: i) Create the database and relation structure; ii) Perform insertion, modification and deletion of data from the relationship; and iii) Perform

More information

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul

EGCI 321: Database Systems. Dr. Tanasanee Phienthrakul 1 EGCI 321: Database Systems Dr. Tanasanee Phienthrakul 2 Chapter 10 Data Definition Language (DDL) 3 Basic SQL SQL language Considered one of the major reasons for the commercial success of relational

More information

Reporting Functions & Operators

Reporting Functions & Operators Functions Reporting Functions & Operators List of Built-in Field Functions Function Average Count Count Distinct Maximum Minimum Sum Sum Distinct Return the average of all values within the field. Return

More information

Building Better. SQL Server Databases

Building Better. SQL Server Databases Building Better SQL Server Databases Who is this guy? Eric Cobb Started in IT in 1999 as a "webmaster Developer for 14 years Microsoft Certified Solutions Expert (MCSE) Data Platform Data Management and

More information

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210 SQL: Concepts Todd Bacastow IST 210: Organization of Data 2/17/2004 1 Design questions How many entities are there? What are the major entities? What are the attributes of each entity? Is there a unique

More information

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints

WHAT IS SQL. Database query language, which can also: Define structure of data Modify data Specify security constraints SQL KEREM GURBEY WHAT IS SQL Database query language, which can also: Define structure of data Modify data Specify security constraints DATA DEFINITION Data-definition language (DDL) provides commands

More information

Sql Server Syllabus. Overview

Sql Server Syllabus. Overview Sql Server Syllabus Overview This SQL Server training teaches developers all the Transact-SQL skills they need to create database objects like Tables, Views, Stored procedures & Functions and triggers

More information

Data about data is database Select correct option: True False Partially True None of the Above

Data about data is database Select correct option: True False Partially True None of the Above Within a table, each primary key value. is a minimal super key is always the first field in each table must be numeric must be unique Foreign Key is A field in a table that matches a key field in another

More information

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity SQL language: basics Creating a table Modifying table structure Deleting a table The data dictionary Data integrity 2013 Politecnico di Torino 1 Creating a table Creating a table (1/3) The following SQL

More information

How to use SQL to create a database

How to use SQL to create a database Chapter 17 How to use SQL to create a database How to create a database CREATE DATABASE my_guitar_shop2; How to create a database only if it does not exist CREATE DATABASE IF NOT EXISTS my_guitar_shop2;

More information

Unit 1 - Chapter 4,5

Unit 1 - Chapter 4,5 Unit 1 - Chapter 4,5 CREATE DATABASE DatabaseName; SHOW DATABASES; USE DatabaseName; DROP DATABASE DatabaseName; CREATE TABLE table_name( column1 datatype, column2 datatype, column3 datatype,... columnn

More information

Introduction to SQL Server 2005/2008 and Transact SQL

Introduction to SQL Server 2005/2008 and Transact SQL Introduction to SQL Server 2005/2008 and Transact SQL Week 4: Normalization, Creating Tables, and Constraints Some basics of creating tables and databases Steve Stedman - Instructor Steve@SteveStedman.com

More information

Chapter 9: Working with MySQL

Chapter 9: Working with MySQL Chapter 9: Working with MySQL Informatics Practices Class XI (CBSE Board) Revised as per CBSE Curriculum 2015 Visit www.ip4you.blogspot.com for more. Authored By:- Rajesh Kumar Mishra, PGT (Comp.Sc.) Kendriya

More information

ColdFusion Summit 2016

ColdFusion Summit 2016 ColdFusion Summit 2016 Building Better SQL Server Databases Who is this guy? Eric Cobb - Started in IT in 1999 as a "webmaster - Developer for 14 years - Microsoft Certified Solutions Expert (MCSE) - Data

More information

/**Memory-Optimized Tables**/ ---- drop database InMemOLTP - if already exists Use MASTER DROP DATABASE if EXISTS InMemOLTP

/**Memory-Optimized Tables**/ ---- drop database InMemOLTP - if already exists Use MASTER DROP DATABASE if EXISTS InMemOLTP /***** Technology Enhancements for SQL Server 2014/2016 Developers - Demo file By: Wylie Blanchard Note: SQL Server 2016 is required for this demo *****/ /**Memory-Optimized Tables**/ ---- drop database

More information

Slides by: Ms. Shree Jaswal

Slides by: Ms. Shree Jaswal Slides by: Ms. Shree Jaswal Overview of SQL, Data Definition Commands, Set operations, aggregate function, null values, Data Manipulation commands, Data Control commands, Views in SQL, Complex Retrieval

More information

SQL Coding Guidelines

SQL Coding Guidelines SQL Coding Guidelines 1. Always specify SET NOCOUNT ON at the top of the stored procedure, this command suppresses the result set count information thereby saving some amount of time spent by SQL Server.

More information

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions

RDBMS-Day3. SQL Basic DDL statements DML statements Aggregate functions RDBMS-Day3 SQL Basic DDL statements DML statements Aggregate functions SQL SQL is used to make a request to retrieve data from a Database. The DBMS processes the SQL request, retrieves the requested data

More information

Views in SQL Server 2000

Views in SQL Server 2000 Views in SQL Server 2000 By: Kristofer Gafvert Copyright 2003 Kristofer Gafvert 1 Copyright Information Copyright 2003 Kristofer Gafvert (kgafvert@ilopia.com). No part of this publication may be transmitted,

More information

Downloaded from

Downloaded from Unit-III DATABASES MANAGEMENT SYSTEM AND SQL DBMS & Structured Query Language Chapter: 07 Basic Database concepts Data : Raw facts and figures which are useful to an organization. We cannot take decisions

More information

DB Creation with SQL DDL

DB Creation with SQL DDL DB Creation with SQL DDL Outline SQL Concepts Data Types Schema/Table/View Creation Transactions and Access Control Objectives of SQL Ideally, database language should allow user to: create the database

More information

SQL Introduction. CS 377: Database Systems

SQL Introduction. CS 377: Database Systems SQL Introduction CS 377: Database Systems Recap: Last Two Weeks Requirement analysis Conceptual design Logical design Physical dependence Requirement specification Conceptual data model (ER Model) Representation

More information

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255.

TINYINT[(M)] [UNSIGNED] [ZEROFILL] A very small integer. The signed range is -128 to 127. The unsigned range is 0 to 255. MySQL: Data Types 1. Numeric Data Types ZEROFILL automatically adds the UNSIGNED attribute to the column. UNSIGNED disallows negative values. SIGNED (default) allows negative values. BIT[(M)] A bit-field

More information

Chapter # 7 Introduction to Structured Query Language (SQL) Part I

Chapter # 7 Introduction to Structured Query Language (SQL) Part I Chapter # 7 Introduction to Structured Query Language (SQL) Part I Introduction to SQL SQL functions fit into two broad categories: Data definition language Data manipulation language Basic command set

More information

Full file at

Full file at ch2 True/False Indicate whether the statement is true or false. 1. The SQL command to create a database table is an example of DML. 2. A user schema contains all database objects created by a user. 3.

More information

Testpassport. Банк экзамен

Testpassport. Банк экзамен Testpassport Банк экзамен самое хорошое качество самая хорошая служба Exam : 70-433 Title : TS: Microsoft SQL Server 2008, Database Development Version : DEMO 1 / 8 1.You have a user named John. He has

More information

Stored Procedures and Functions. Rose-Hulman Institute of Technology Curt Clifton

Stored Procedures and Functions. Rose-Hulman Institute of Technology Curt Clifton Stored Procedures and Functions Rose-Hulman Institute of Technology Curt Clifton Outline Stored Procedures or Sprocs Functions Statements Reference Defining Stored Procedures Named Collections of Transact-SQL

More information

CSC Web Programming. Introduction to SQL

CSC Web Programming. Introduction to SQL CSC 242 - Web Programming Introduction to SQL SQL Statements Data Definition Language CREATE ALTER DROP Data Manipulation Language INSERT UPDATE DELETE Data Query Language SELECT SQL statements end with

More information