Vous êtes sur la page 1sur 37

SQL IN VFP

DIN VFP HELP


Structured Query Language (SQL) commands.
Visual FoxPro supports the following SQL commands:
SL!" # SQL
$ou can create a SL!" command %uery in these areas:
&n the !ommand window.
&n a Visual FoxPro program (li'e any other Visual FoxPro command).
&n the Query (esigner.
)L"* ")+L # SQL
,odifies an existing ta-le. $ou can modify the name. type. precision. scale. null /alue support. and
referential integrity rules for each field in the ta-le.
!*)" !0*S1* # SQL
!reates a temporary ta-le. ach field in the temporary ta-le is defined with a name. type. precision.
scale. null /alue support. and referential integrity rules. "hese definitions can -e o-tained from the
command itself or from an array.
!*)" ")+L #SQL
!reates a ta-le. ach new ta-le field is defined with a name. type. precision. scale. null /alue support.
and referential integrity rules. "hese definitions can -e o-tained from the command itself or from an
array.
(L" # SQL
,ar's records in a ta-le for deletion using SQL syntax.
&2S*" # SQL
)ppends a new record to the end of an existing ta-le. "he new record contains data listed in the
&2S*" command or from an array.
0P()" # SQL
0pdates records in a ta-le. "he records can -e updated -ased on the results of a SL!" # SQL
statement.
INTRODUCERE
Astfel pentru MANIPULAREA DATELOR sint utilizate comenzile
SELECT Extragerea datelor din BD
INSERT Adaugarea de noi linii/inscrieri in BD
DELETE Stergerea de linii dintr-o tebela
UPDATE Modificarea valorilor unor atribute
Pentru DEFINREA BAZEI DE DATE
CREATE TABEL Adaugarea unei noi tabele in BD
DROP TABLE Stergerea unei tabele din BD
ALTER TABLE Modificarea structurii unui tabel
CREATE VIEW rearea unei tabele virtuale
CREATE CURSOR rearea unei tabele temporare
Pentru !"#$!%&% #$A"'A#((%!$
BEGIN TRANZACTION Marc)eaza inceputul unei tranzactii
END TRANZACTION Marc)eaza sfirsitul unei tranzactii
*
ROLLBACK Abandoneaza tranzactia in curs
1. CREAREA TABELELOR SI DECLARAREA RESTRICTIILOR
Se efectuiaza cu a+utorul comenzii CREATE TABLE iar pentru modificarea structurii tabelului cu
ALTER TABLE
Syntaxa
CREATE TABLE | DBF TableName1 [NAME LongTableName [FREE
!F"el#Name1 F"el#T$%e [!nF"el#&"#'( [) nP*e+","on-
[NULL | NOT NULL
[CHEC. lE/%*e,,"on1 [ERROR +Me,,ageTe/'1
[DEFAULT eE/%*e,,"on1
[PRIMAR0 .E0 | UNI1UE
[REFERENCES TableName2 [TA3 TagName1 44 Tablename2 'abela5%a*"n'e a lega'6*""
[NOCPTRANS
[) F"el#Name2 ...
[) PRIMAR0 .E0 eE/%*e,,"on2 TA3 TagName2
|) UNI1UE eE/%*e,,"on7 TA3 TagName7 44 Se +*ea8a 6n "n#e/ +an#"#a'
[) FOREI3N .E0 eE/%*e,,"on9 TA3 TagName9 [NODUP 44 Se +*ea8a 6n "n#e/ *eg6la*
REFERENCES TableName7 [TA3 TagName:
[) CHEC. lE/%*e,,"on2 [ERROR +Me,,ageTe/'2-
| FROM ARRA0 A**a$Name
E/em%l6 #"n Ma'e*"al6l HELP al VFP.
#)e follo,ing example creates a ne, database named Mydata1. $EA#E #AB%E is used to create
t)ree tables -Salesman, Customer, and Orders.. #)e /!$E(0" 1E2 and $E/E$E"ES clauses in
t)e second $EA#E #AB%E command create a persistent one-to-man3 relations)ip bet,een t)e
Salesman and Customer tables. #)e DE/A&%# clauses in t)e t)ird $EA#E #AB%E command
establis) default values4 and t)e 5E1 and E$$!$ clauses establis) business rules for entering data
into specific fields. #)e M!D(/2 DA#ABASE is used to displa3 t)e relations)ip bet,een t)e t)ree
tables.
CLOSE DATABASES
CLEAR
* Create mydata database in the current directory or folder
CREATE DATABASE mydata1
* Create a salesman table with a rimary !ey
CREATE TABLE salesman "
#Sales$D c#%& 'R$(AR) *E)+ "
Sale,ame C#-.&&
* Create a customer table and relate it to the salesman table/
CREATE TABLE customer "
#Sales$D c#%&+ "
Cust$d i 'R$(AR) *E)+ "
Cust,ame c#-.& 0,$10E+ "
SalesBranch c#2&+ "
FOREIGN KEY Sales$d TA3 Sales$d REFERENCES salesman&
* Create an orders table related to customer with its own rimary
* !ey and some business rules such as defaults 4 chec!s/
CREATE TABLE orders "
#Order$d i 'R$(AR) *E)+ "
Cust$d i REFERENCES customer TA3 Cust$d+ "
6
OrderAmt y#5&+ "
Order1ty i "
DEFAULT 1. "
CHECK #Order1ty 6 7& "
ERROR 8Order 1uantity must be at least 1.8+ "
Disc'ercent n#%+-& ,0LL "
DEFAULT /,0LL/+ "
CHECK #OrderAmt 6 .& ERROR 8Order Amount (ust be 6 .8 &
* Dislay new database+ tables+ and relationshis
(OD$9) DATABASE
* Delete e:amle files
SET SA9ET) O99 44 To suress ;erification messa<e
CLOSE DATABASES 44 Close database before deletin<
DELETE DATABASE mydata1 DELETETABLES
2. UTILI;AREA INSTRUCTIUNILOR S1L PENTRU CREAREA BD SI A
TABELELOR
777777program care prezinta crearea si manipularea cu datele a unei BD prin intermediul S8% -
777777comenzilor
%!SE DA#A A%%
%!SE #AB%ES A%%
%!SE A%%
set default to )ome-.9:;S8%<test;:
set pat) to #(/
DE%E#E DA#ABASE xxxxxx DE%E#E#AB%ES
,ait ,indo, :A fost distrusa BD xxxxxx: A# 6=4>= timeout ?
$EA#E DA#ABASE xxxxxx
$EA#E #AB%E raioane -@
nrai 5A$-6.@
P$(MA$2 1E2@
5E1-nraiA%#$(M-&PPE$-nrai...@
E$$!$ Bindicativul +udetului se scrie cu ma+uscule CB4 @
raion 5A#-6D. @
"!# "&%% @
5E1-raionA%#$(M-P$!PE$-raion... @
E$$!$ BPrima literea din fiecare cuvint alB 9c)r-*?.9@
Bdenumirii raionului este ma+usculaB9c)r-*?.9@
Brestul literelor sint mici CB4@
regiune 5A$-*D.@
DE/A&%# BentruB@
5E1 -("%(S#-regiune4BentruB4B"ordB4BSudB..@
E$$!$ B$egiunea poate avea doar o valoare din listaB95$-*?.9@
Bentru4"ord4SudB@
.
7777777777 #abelul 6
?
$EA#E #AB%E localitati -@
codpost 5A$-D.@
P$(MA$2 1E2@
5E1-cospostA%#$(M-&PPE$-codpost...@
E$$!$ Bodul postal se scrie fara spatii la inceput CB4 @
loc 5A#-6D. @
"!# "&%% @
5E1-locA%#$(M-P$!PE$-loc... @
E$$!$ BPrima literea din fiecare cuvint alB 9 5$ -*?.9@
Bdenumirii localitatii este ma+usculaB9 5$ -*?.9@
Brestul literelor sint mici CB4@
nrai 5A$-6.@
DE/A&%# B(SB4@
/!$E(0" 1E2 nrai #A0 nrai $E/E$E"ES raioane #A0 nrai@
.@
7777777777 #abelul ?

$EA#E #AB%E clienti -@
codcl "&MBE$->.@
P$(MA$2 1E2@
5E1-codclE*===.4@
E$$!$ Bodul clientului trebuie sa fie mai mare decit *=== CB4 @
dencl 5A$-?=. @
5E1-S&BS#$-dencl4*4*.A&PPE$-S&BS#$-dencl4*4*... @
E$$!$ BPrima literea din denumirea clientului esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
codfiscal 5A$-F.@
"&%%4@
5E1-S&BS#$-codfiscal4*4*.A&PPE$-S&BS#$-codfiscal4*4*... @
E$$!$ BPrima literea din codul fiscal esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
adresa 5A$-G=.@
"&%%@
5E1-S&BS#$-adresa4*4*.A&PPE$-S&BS#$-adresa4*4*... @
E$$!$ BPrima literea din adresa esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
codpost 5A$-D.4@
telefon 5A$-*=. @
"&%%4 @
/!$E(0" 1E2 codpost #A0 codpost $E/E$E"ES localitati #A0 codpost@
.@
7777777777 #abelul G

$EA#E #AB%E persoane -@
cnp 5A$-*G.@
P$(MA$2 1E2@
5E1-cnpA%#$(M-&PPE$-cnp...@
E$$!$ Bodul postal se scrie fara spatii la inceput CB4 @
nume 5A$-6=. @
5E1-numeA %#$(M-P$!PE$-nume... @
E$$!$ BPrima literea din fiecare cuvint alB 9 5$ -*?.9@
Bnumelui persoanei este ma+usculaB9 5$ -*?.9@
Brestul literelor sint mici CB4@
G
prenume 5A$-6=.@
5E1-prenumeA %#$(M-P$!PE$-prenume... @
E$$!$ BPrima literea din fiecare cuvint alB 9 5$ -*?.9@
Bprenumelui persoanei este ma+usculaB9 5$ -*?.9@
Brestul literelor sint mici CB4@
adresa 5A$-G=.@
"&%%@
5E1-S&BS#$-adresa4*4*.A&PPE$-S&BS#$-adresa4*4*... @
E$$!$ BPrima literea din adresa esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
sex 5A$-*. DE/A&%# BBB@
5E1-("%(S#-SEH4B/B4BBB..@
E$$!$ BAtributul Sex poate avea valorile / pentru femeiB9 5$ -*?.9@
Bsi B pentru barabtiB 4@
codpost 5A$-D.4@
telacasa 5A$-*=. "&%%4@
telbirou 5A$-*=. "&%%4@
telmobil 5A$-*=. "&%%4@
email 5A$-6=. "&%%4@
/!$E(0" 1E2 codpost #A0 codpost $E/E$E"ES localitati #A0 codpost@
.@
7777777777 #abelul D
$EA#E #AB%E persclient -@
cnp 5A$-*G.4@
codcl "&MBE$->.4@
functie A5$-6D.@
5E1-S&BS#$-functie4*4*.A&PPE$-S&BS#$-functie4*4*... @
E$$!$ BPrima litera din functie se scrie cu ma+uscule CB4 @
P$(MA$2 1E2 cnp9S#$-codcl4>.9functie #A0 primaru4 @
/!$E(0" 1E2 cnp #A0 cnp $E/E$E"ES persoane #A0 cnp4@
/!$E(0" 1E2 codcl #A0 codcl $E/E$E"ES clienti #A0 codcl@
.
7777777777 #abelul >

$EA#E #AB%E produse -@
codpr "&MBE$->.@
P$(MA$2 1E2@
5E1-codclE=.4@
E$$!$ Bodul produsului trebuie sa fie mai mare decit = CB4 @
denpr 5A$-?=. @
5E1-S&BS#$-denpr4*4*.A&PPE$-S&BS#$-denpr4*4*... @
E$$!$ BPrima literea din denumirea produsului esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
um 5A$-*=.4@
grupa 5A$-*D.@
5E1-S&BS#$-grupa4*4*.A&PPE$-S&BS#$-grupa4*4*... @
E$$!$ BPrima literea din grupa esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
proc#IA "&MBE$-?46.@
DE/A&%# =.6J4@
imagine 0E"E$A%@
.
D
7777777777 #abelul K

$EA#E #AB%E gestiuni -@
gestiune 5A$-G.@
P$(MA$2 1E24@
den<gest 5A$-6D.@
5E1-S&BS#$-den<gest4*4*.A&PPE$-S&BS#$-den<gest4*4*... @
E$$!$ BPrima literea din denumirea produsului esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
adresa 5A$-G=. @
"&%%@
5E1-S&BS#$-adresa4*4*.A&PPE$-S&BS#$-adresa4*4*... @
E$$!$ BPrima literea din adresa esteB9 5$ -*?.9@
Bobligatoriu ma+usculaCB 4@
codpost 5A$-D.4@
telefon 5A$-*=.@
"&%%4@
cnp 5A$-*G.4@
email 5A$-6=. "&%%4@
/!$E(0" 1E2 codpost #A0 codpost $E/E$E"ES localitati #A0 codpost4@
/!$E(0" 1E2 cnp #A0 cnp $E/E$E"ES persoane #A0 cnp@
.
7777777777 #abelul J
$EA#E #AB%E facturi-@
nrfact "&MBE$-J.@
P$(MA$2 1E24@
datafact DA#E@
DE/A&%# DA#E-.@
5E1-BE#LEE"-datafact4MN6==*/=*/=*O4MN6=*=/*6/?*O.. @
E$$!$ BData fact se afal in interv * ian 6==*-?* decembrie 6=*=CB4 @
gestiune 5A$-G. "!# "&%%4@
codcl "&MBE$->.4@
obs 5A$-D=. "&%%4@
/!$E(0" 1E2 gestiune #A0 gestiune $E/E$E"ES gestiuni #A0 gestiune4@
/!$E(0" 1E2 codcl #A0 codcl $E/E$E"ES clienti #A0 codcl@
.
7777777777 #abelul F
$EA#E #AB%E liniifact-@
nrfact "&MBE$-J.4@
linie "&MBE$-6.@
5E1-linieE=.4@
E$$!$ Bodul linie trebuie sa fie mai mare decit = CB4 @
codpr "&MBE$->.4@
cantitate "&MBE$-*=.4@
pretunit "&MBE$-*6.4@
P$(MA$2 1E2 S#$-nrfact4J.9S#$-linie46. #A0 primaru4 @
/!$E(0" 1E2 nrfact #A0 nrfact $E/E$E"ES facturi #A0 nrfact4@
/!$E(0" 1E2 codpr #A0 codpr $E/E$E"ES produse #A0 codpr@
.
7777777777 #abelul *=
$EA#E #AB%E incasari-@
>
codinc "&MBE$-J.@
P$(MA$2 1E24@
datainc DA#E@
DE/A&%# DA#E-.@
5E1-BE#LEE"-datainc4MN6==*/=*/=*O4MN6=*=/*6/?*O.. @
E$$!$ BData inc se afal in interv * ian 6==*-?* decembrie 6=*=CB4 @
coddoc 5A$-G.@
5E1-coddocA &PPE$ -%#$(M -coddoc...@
E$$!$ Bodul documentului se scrie cu ma+usculeCB4 @
nrdoc 5A$-*>.4@
datadoc DA#E@
DE/A&%# DA#E-.-D@
.
7777777777 #abelul **
$EA#E #AB%E incasfact-@
codinc "&MBE$-J.4@
nrfact "&MBE$-J.4@
transa "&MBE$-*>. "!# "&%%4@
P$(MA$2 1E2 S#$-codinc4J.9S#$-nrfact4J. #A0 primaru4 @
/!$E(0" 1E2 codinc #A0 codinc $E/E$E"ES incasari #A0 codinc4@
/!$E(0" 1E2 nrfact #A0 nrfact $E/E$E"ES facturi #A0 nrfact@
.
A'en'"e<<<
%a crearea indexilor compusi4 la crearea indexilor Primari / P$(MA$2 1E2 /4 $egulari //!$E(0"
1E2/ si andidat /&"!8&E/.
Din pacate declararea c)eilor straine nu inseamna si intituirea restrictiei referentiale. Pentru a o institui
este necesar de a institui restrictiile mentionate cu *eferential &ntegrity +uilder.
7. MODIFICAREA STRUCTURII TABELELOR
! proiectare buna in general creaza putine probleme ce tin de modificarea structurii BD. Ea de fapt
ramine intacta. u toate acestea pot aparea unele necesitati de modificare a lungimii unui atribut4
adaugarii unui atribut4 stergerii unui atribut s.a.
Pentru a modifica structura tabelelor de date este utilizata comanda A%#E$ #AB%E. (n cele ce urmeaza
vom prezenta citeva formate de sintaxa a acestei comenzi si citeva exemple.
)L"* ")+L "a-le2ame3
)(( 4 )L"* 5!1L0,26 Field2ame3
Field"ype 5(nField7idth 5. nPrecision6)6
520LL 4 21" 20LL6
5!8!9 lxpression3 5**1* c,essage"ext366
5(F)0L" expression36
5P*&,)*$ 9$ 4 02&Q06
5*F*2!S "a-le2ame: 5"); "ag2ame366
521!P"*)2S6
521V)L&()"6
#or#
)L"* ")+L "a-le2ame3
)L"* 5!1L0,26 Field2ame:
520LL 4 21" 20LL6
5S" (F)0L" expression:6
K
5S" !8!9 lxpression: 5**1* c,essage"ext:66
5(*1P (F)0L"6
5(*1P !8!96
521V)L&()"6
#or#
)L"* ")+L "a-le2ame3
5(*1P 5!1L0,26 Field2ame<6
5S" !8!9 lxpression< 5**1* c,essage"ext<66
5(*1P !8!96
5)(( P*&,)*$ 9$ expression< "); "ag2ame: 5F1* lxpression=66
5(*1P P*&,)*$ 9$6
5)(( 02&Q0 expression= 5"); "ag2ame< 5F1* lxpression>666
5(*1P 02&Q0 "); "ag2ame=6
5)(( F1*&;2 9$ 5expression>6 "); "ag2ame= 5F1* lxpression?6
*F*2!S "a-le2ame: 5"); "ag2ame>66
5(*1P F1*&;2 9$ "); "ag2ame? 5S)V66
5*2), !1L0,2 Field2ame= "1 Field2ame>6
521V)L&()"6
E/em%le #"n HELP VFP.
ALTER TABLE - SQL Command Examples
xample 3 adds a field called fa: to the customer ta-le and allows the field to ha/e null /alues.
xample : ma'es the cust=id field the primary 'ey of the customer ta-le.
xample < adds a field /alidation rule to the >uantity field of the orders ta-le so that /alues in the
>uantity field must -e non#negati/e.
xample = adds a one#to#many persistent relation -etween the customer and orders ta-les -ased on
the primary 'ey cust=id in the customer ta-le and a new foreign 'ey index cust=id in the orders
ta-le.
xample > remo/es the field /alidation rule from the >uantity field in the orders ta-le.
xample ? remo/es the persistent relation -etween the customer and orders ta-les. -ut 'eeps the
cust=id index tag in the orders ta-le.
xample @ adds a field called fa:- to the customer ta-le and pre/ents the field from containing null
/alues. "he new structure of the ta-le is displayed. "wo )L"* !1L0,2 clauses are used to allow the
field to ha/e null /alues and set the default /alue for the field to the null /alue. 2ote that multiple
)L"* !1L0,2 clauses are re%uired to change more than one property of a field in a single )L"*
")+L command. "he new field is then remo/ed from the ta-le to restore the ta-le to its original state.
* Example 1
SET PATH TO (HOME(2 ! "Da#a$" %% Se#& pa#' #( #a)le
ALTER TABLE *+&#(me, ADD COLUMN -ax *(2. NULL
* Example 2
ALTER TABLE *+&#(me, ADD PRIMARY KEY *+&#/01 TAG *+&#/01
ALTER TABLE *+&#(me, ALTER COLUMN *+&#/01 *(2 PRIMARY KEY
* Example 3
ALTER TABLE (,1e,&4
ALTER COLUMN 5+a6#0#7 SET CHECK 5+a6#0#7 89 .4
ERROR :;+a6#0#0e& m+&# )e 6(6<6e=a#0>e:
* Example ?
ALTER TABLE (,1e,&4
J
ADD FOREIGN KEY *+&#/01 TAG *+&#/01 REFERENCES *+&#(me,
* Example 2
ALTER TABLE (,1e,& ALTER COLUMN 5+a6#0#7 DROP CHECK
* Example @
ALTER TABLE (,1e,& DROP FOREIGN KEY TAG *+&#/01 SAAE
* Example B
CLEAR
ALTER TABLE *+&#(me, ADD COLUMN -ax2 *(2. NOT NULL
DISPLAY STRUCTURE
ALTER TABLE *+&#(me,4
ALTER COLUMN -ax2 NULL4
ALTER COLUMN -ax2 SET DEFAULT CNULLC
ALTER TABLE *+&#(me, DROP COLUMN -ax2
In cazul exemplului BD generate de noi
Adaugarea atributului DataNast adica data nasterii in tabela PERSOANE se realizeaza astfel
ALTER TABLE PERSOANE ADD DataNast DATE
Redenumirea unui atribut, il poate face doar VFP printere cele mai renumite S!D"uir
ALTER TABLE PERSOANE RENAME #O$%&N DataNast TO DataNasterii
Stergerea unui atribut, sa zicem pe cel pe care numai ce l"am adau'at se (a face prin
comanda
ALTER TABLE PERSOANE DROP #O$%&N DataNasterii
Modificarea tipului)lun'imii unui atribut
ALTER TABLE PERSOANE ALTER #O$%&N Prenume #*AR+,-.
ALTER TABLE PERSOANE ALTER #O$%&N Nume #*AR+-/.
Adaugarea/modificarea (alorii implicite
ALTER TABLE PERSOANE ALTER #O$%&N Se0 SET DEFA%$T 1F2
Se definesc (alorile prin Default, deoarece se presupune ca e0ista mai multe femei decit
barbate3
Interzicerea valorilor nule pentru atributul Se0 se e0ecuta dupa comanda3
ALTER TABLE PERSOANE ALTER #O$%&N Se0 NOT N%$$
Adaugarea/anularea restrictiilor se e0ecuta tot cu a4utorul A$TER
Restrictiile PR5&AR6 7E6 c8eie primara
%N59%E unicitate
FORE5N 7E6 referentiala
#*E#7 de comportament3
De e0emplu dezacti(area c8eiei primare se efectuiaza cu a4utorul comenzii
F
ALTER TABLE PERSOANE DROP PR5&AR6 7E6
Pentru restabilirea :eiei
ALTER TABLE PERSOANE ADD PR5&AR6 7E6 +#NP. ;; numele cimpului in paranteze
Atentie!!!
NOVA$5DATE se permite operarea unor modificari ale structurii c8iar daca acestea
ar (iola inte'ritatea datelor3
4.COMENZI DE ACTALIZARE
Trei sunt comenzile de actualizare INSERT, UPDATE si DELETE
A. Adaugarea unei linii/inscrieri
Din !ELP al "#P
Appends a record to t8e end of a table t8at contains t8e specified field (alues3
Syntaxa
INSERT INTO #b=>name [!=name1 [) =name2) ...-
VALUES !eE/%*e,,"on1 [) eE/%*e,,"on2) ...-
#or#
&2S*" &2"1 d-fAname F*1, )**)$ )rray2ame 4 F*1, ,,V)*
A*g6men',
&2S*" &2"1 d-fAname
Specifies the name of the ta-le to which the new record is appended. d-fAname can include a path and
can -e a name expression.
&f the ta-le you specify isnBt open. it is opened exclusi/ely in a new wor' area and the new record is
appended to the ta-le. "he new wor' area isnBt selectedC the current wor' area remains selected.
&f the ta-le you specify is open. &2S*" appends the new record to the ta-le. &f the ta-le is open in a
wor' area other than the current wor' area. it isnBt selected after the record is appendedC the current
wor' area remains selected.
5(fname3 5. fname: 5. ...66)6
Specifies the names of the fields in the new record into which the /alues are inserted.
V)L0S (expression3 5. expression: 5. ...66)
Specifies the field /alues inserted into the new record. &f you omit the field names. you must specify the
field /alues in the order defined -y the ta-le structure. &f S" 20LL is 12. &2S*" D SQL attempts to
insert null /alues into any fields not specified in the V)L0S clause.
F*1, )**)$ )rray2ame
Specifies the array whose data is inserted into the new record. "he contents of the elements of the array.
starting with the first element. are inserted into the corresponding fields of the record. "he contents of
the first array element are inserted into the first field of the new recordC the contents of the second array
element are inserted into the second field. and so on.
)ny default /alues for fields are ignored when you include the F*1, )**)$ clause.
F*1, ,,V)*
Specifies that the contents of /aria-les are inserted into fields with the same names as the /aria-les. &f a
/aria-le doesnBt exist with the same name as the field. the field is left empty.
Rema*?,
*=
"he new record contains the data listed in the V)L0S clause or contained in the specified array or
/aria-les. "he record pointer is positioned on the new record.
INSERT @ S1L Comman# E/am%le, #"n HELP VFP
"he following example opens the emloyee ta-le and adds one record.
0SE emloyee
INSERT INTO emloyee #em=no+ fname+ lname+ officeno& "
?AL0ES #2.--+ 8@ohn8+ 8Smith8+ -1.1&
"he following example opens the customer ta-le in the #e&#1a#a data-ase. "he contents of the current
record are scattered to /aria-les. and the ta-leBs structure is copied to a new ta-le named cust-.
&2S*" # SQL is used to insert a new record in the cust- ta-le. and +*17S is issued to display the
new record.
CLOSE DATABASES
CLEAR
OPEN DATABASE (HOME(2 ! "Da#a$#e&#1a#a"
USE C+&#(me, %% Ope6 *+&#(me, #a)le
* S*a##e, *+,,e6# ,e*(,1 #( mem(,7 >a,0a)le&
SCATTER MEMAAR
* C(p7 &#,+*#+,e (- *+,,e6# #a)le #( example #a)le
COPY STRUCTURE TO *+&#2
* I6&e,# ,e*(,1 -,(m mem(,7 >a,0a)le
INSERT INTO *+&#2 FROM MEMAAR
SELECT CUST2
BRODSE
* Cl(&e a61 1ele#e example #a)le
USE
DELETE FILE *+&#2C1)-
Atentie!!!
rdinea !alorilor in clauza "ALUES tre#uie sa $ie identica cu cea declarata la
crearea %sau modi$icarea structurii& ta#elelor' (odi$icarea este posi#ila numai
prin enumararea dupa numele ta#elei, a atri#utelor ce !or primi !alorile
specificate
B. STER3EREA UNOR LINIIAINSCRIERI
D"n HELP VFP
MarPs records for deletion.
Syntax
DELETE
S+o%e] FOR lE/%*e,,"on1] WHILE lE/%*e,,"on2]
IN n&o*?A*ea [ +TableAl"a,]
NOOPTIMIZE]
A*g6men',
Scope
Specifies a range of records to mar' for deletion. "he scope clauses are: )LL. 2E" n*ecords.
*!1*( n*ecord2um-er. and *S".
"he default scope for (L" is the current record (2E" 3).
**
F1* lxpression3
Specifies a condition where-y only the records that satisfy the logical condition lxpression3 are
mar'ed for deletion.
*ushmore optimiFes a %uery created with (L" ... F1* if lxpression3 is an optimiFa-le expression
and the ta-le is indexed on (L"(( ). For -est performance. use an optimiFa-le expression in the
F1* clause.
78&L lxpression:
Specifies a condition where-y records are mar'ed for deletion for as long as lxpression: e/aluates to
true (.".).
&2 n7or')rea
Specifies the wor' area of the ta-le in which records are mar'ed for deletion.
&2 c"a-le)lias
Specifies the alias of the ta-le in which records are mar'ed for deletion.
&f you omit n7or')rea and c"a-le)lias. records are mar'ed for deletion in the ta-le in the currently
selected wor' area.
211P"&,&G
(isa-les *ushmore optimiFation of (L".
Rema*?,
*ecords mar'ed for deletion arenBt physically remo/ed from the ta-le until P)!9 is issued. *ecords
mar'ed for deletion can -e recalled (unmar'ed) with *!)LL.
DELETE Comman# E/am%le #"n HELP VFP
"he following example opens the customer ta-le in the testdata data-ase. (L" is used to mar'
all records for deletion where the country field contains 0S). )ll the records mar'ed for deletion are
displayed. *!)LL )LL is used to unmar' all the records mar'ed for deletion.
CLOSE DATABASES
OPEN DATABASE (HOME(2 ! "Da#a$#e&#1a#a"
USE *+&#(me, %% Ope6& C+&#(me, #a)le
DELETE FOR *(+6#,7 9 "USA" %% Ma,E -(, 1ele#0(6
CLEAR
LIST FIELDS *(mpa67F *(+6#,7 FOR DELETED( %% L0&# ma,Ee1 ,e*(,1&
RECALL ALL %% U6ma,E all ,e*(,1& ma,Ee1 -(, 1ele#0(6
PRO3RAM DE COMPLETARE CU DATE A BD BBBBBB.DBC
Se' #ea=6l' 'o (ome!-C DES1L>'e,'EF
IF <DBUSED!G//////H-
OPEN DATABASE ////// EBCLUSIVE
ENDIF
DELETE FROM "n+a,=a+'
SELE "n+a,=a+'
;AP
DELETE FROM "n+a,a*"
SELE "n+a,a*"
;AP
DELETE FROM l"n""=a+'
SELE l"n""=a+'
;AP
DELETE FROM =a+'6*"
SELE =a+'6*"
;AP
DELETE FROM ge,'"6n"
SELE ge,'"6n"
;AP
DELETE FROM %*o#6,e
SELE %*o#6,e
;AP
*6
DELETE FROM %e*,+l"en'"
SELE %e*,+l"en'"
;AP
DELETE FROM %e*,oane
SELE %e*,oane
;AP
DELETE FROM +l"en'"
SELE +l"en'"
;AP
DELETE FROM lo+al"'a'"
SELE lo+al"'a'"
;AP
DELETE FROM *a"oane
SELE *a"oane
;AP
`````````Inserare de date
INSERT INTO raioane VALUES (AN`,`Anenii Noi`, Centru`)
INSERT INTO raioane VALUES (ST`,`Straseni`, Centru`)
INSERT INTO raioane VALUES (CR`,`Criuleni`, Centru`)
INSERT INTO raioane VALUES (IA`,`Ialoveni`, Centru`)
INSERT INTO raioane VALUES (HI`,`Hincesti`, Centru`)
INSERT INTO raioane VALUES (NI`,`Nisporeni`, Centru`)
INSERT INTO raioane VALUES (SO`,`Soroca`, Nord`)
INSERT INTO raioane VALUES (ED`,`Edinet`, Nord`)
INSERT INTO raioane VALUES (BR`,`Briceni`, Nord`)
INSERT INTO raioane VALUES (RE`,`Rezina`, Nord`)
INSERT INTO raioane VALUES (CH`,`Cahul`, Sud`)
INSERT INTO raioane VALUES (CA`,`Cantemir`, Sud`)
INSERT INTO raioane VALUES (LE`,`Leova`, Sud`)
INSERT INTO raioane VALUES (GA`,`UTAG`, Sud`)
INSERT INTO localitati VALUES (2200`,`Anenii Noi`, AN`)
INSERT INTO localitati VALUES (2300`,`Anenii Noi`, AN`)
INSERT INTO localitati VALUES (2000`,`Straseni`, ST`)
INSERT INTO localitati VALUES (2100`,`Straseni`, ST`)
INSERT INTO localitati VALUES (2400`,`Criuleni`, CR`)
INSERT INTO localitati VALUES (2500`,`Criuleni`, CR`)
INSERT INTO localitati VALUES (2600,`Cantemir`, CA`)
INSERT INTO localitati VALUES (2700`,`Ialoveni`, IA`)
INSERT INTO localitati VALUES (3000`,`Hincesti`, HI`)
INSERT INTO localitati VALUES (3200`,`Hincesti`, HI`)
INSERT INTO localitati VALUES (3400`,`Edinet`, ED`)
INSERT INTO localitati VALUES (3600`,`Cahul`, CH`)
INSERT INTO clienti VALUES (1001,`Client 1 SRL`,`R1001`,`Cucima 13`,`2000`,NULL)
INSERT INTO clienti (codcl,dencl,codfiscal,codpost,telefon);
VALUES (1002,`Client 2 SRL`,`R1002`,`Cucima 13`,`2700`,`032-212121`)
INSERT INTO clienti VALUES (1003,`Client 1 SRL`,`R1003`,`Putin 13`,`2200`,NULL)
INSERT INTO clienti (codcl,dencl,codfiscal,codpost,telefon);
VALUES (1004,`Client 2 SRL`,`R1004`,`Cucima 13`,`2200`,`032-212121`)
INSERT INTO clienti VALUES (1005,`Client 1 SRL`,`R1005`,`Brejnev 13`,`2000`,NULL)
INSERT INTO clienti VALUES (1006,`Client 1 SRL`,`R1006`,`Ustinov 13`,`2200`,NULL)
INSERT INTO clienti VALUES (1007,`Client 1 SRL`,`R1007`,`Andropov 13`,`3400`,NULL)
INSERT INTO clienti VALUES (1008,`Client 1 SRL`,`R1008`,`Cosighin 13`,`2200`,NULL)
*?
INSERT INTO persoane
VALUES (CNP1`,`Ion`, Vasile`,`Sloboda 13`,`B`,`2200`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP2`,`Chiron`, Ileana`,`Sloboda
13`,`F`,`2200`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP3`,`Vanea`, Petru`,`Sloboda 13`,`B`,`2100`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP4`,`Ghita`, Valea`,`Sloboda 13`,`F`,`2000`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP5`,`Tiron`, Iulia`,`Sloboda 13`,`F`,`2700`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP6`,`Papion`, Nelea`,`Sloboda
13`,`F`,`2500`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persoane
VALUES (CNP7`,`Ghidon`, Peste`,`Sloboda
13`,`B`,`3000`,`123456`,`987654`,`094222222`,NULL)
INSERT INTO persclient VALUES (CNP1`,1001,`Director general`)
INSERT INTO persclient VALUES (CNP2`,1002,`Director general`)
INSERT INTO persclient VALUES (CNP3`,1003,`Sef aprovizionare`)
INSERT INTO persclient VALUES (CNP4`,1004,`Sef aprovizionare`)
INSERT INTO persclient VALUES (CNP5`,1005,`Director financiar`)
INSERT INTO persclient VALUES (CNP6`,1006,`Director general`)
INSERT INTO persclient VALUES (CNP7`,1007,`Director financiar`)
INSERT INTO persclient VALUES (CNP8`,1008,`Sef aprovizionare`)
INSERT INTO produse (codpr,denpr,um,grupa,proctva);
VALUES (1,`Produs 1`,`buc`,`Tigari`,0.19)
INSERT INTO produse (codpr,denpr,um,grupa,proctva);
VALUES (2,`Produs 2`,`kg`,`Bere`,0.19)
INSERT INTO produse (codpr,denpr,um,grupa,proctva);
VALUES (3,`Produs 3`,`kg`,`Bere`,0.19)
INSERT INTO produse (codpr,denpr,um,grupa,proctva);
VALUES (4,`Produs 4`,`buc`,`Dulciuri`,0.19)
7includerea imaginilor in cimpurile 0E"E$A%. CCCC (n S8% nu exista astfel de posibilitati
SELECT Produse
GO TOP
nrFisierTifADIR(A_fTifuri,`.tif)
IF nrFisierTif>0
FOR I1 TO nrFisierTif
APPEND GENERAL imagine FROM A_fTifuri(I,1)
SKIP
ENDFOR
ENDIF
INSERT INTO gestiuni
VALUES (001`,`Depozitul 1,`Soseaua Hincesti, 13`,`2200`,`CNP10`,`212121`,`xgest001mail.ru`)
INSERT INTO gestiuni
VALUES (002`,`Depozitul 2,`Soseaua Hincesti, 13`,`2300`,`CNP11`,`212121`,`xgest001mail.ru`)
INSERT INTO gestiuni
*G
ADIR% & )unction Example
T8e follo<in' e0ample uses AD5R+ . to create an arra=
containin' database information3 T8e names of t8e databases
are t8en displa=ed3
#$OSE DATA!ASES
SET PAT* TO +*O&E+,. > ?Data?.
'nDbcnumber @ ADIR%'aDatabase, ?A3D!#?& && Create
array
CLEAR
FOR nCount = 1 TO gnDbcnumber &&
Loo !or number o! databases
" gaDatabase#nCount,1$ && D%slay
database names
VALUES (003`,`Depozitul 3,`Soseaua Hincesti, 13`,`2700`,`CNP12`,`212121`,`xgest001mail.ru`)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1111,^2001/08/01],`001`,1001)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1112,^2001/08/01],`001`,1001)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1113,^2001/08/01],`001`,1002)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1114,^2001/08/01],`001`,1002)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1115,^2001/08/01],`001`,1003)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1116,^2001/08/01],`001`,1003)
INSERT INTO facturi (nrfact,datafact,gestiune,codcl)
VALUES(\ (1117,^2001/08/01],`001`,1004)
INSERT INTO liniifact VALUES(\ (1111,1,1,50,10000)
INSERT INTO liniifact VALUES(\ (1111,2,2,75,10500)
INSERT INTO liniifact VALUES(\ (1111,3,5,500,6500)
INSERT INTO liniifact VALUES(\ (1112,1,2,80,10300)
INSERT INTO liniifact VALUES(\ (1112,2,3,40,7500)
INSERT INTO liniifact VALUES(\ (1113,1,2,100,9750)
INSERT INTO liniifact VALUES(\ (1113,1,2,70,10700)
INSERT INTO liniifact VALUES(\ (1113,2,4,30,15800)
INSERT INTO liniifact VALUES(\ (1114,3,5,700,10000)
INSERT INTO liniifact VALUES(\ (1114,1,2,150,9300)
INSERT INTO liniifact VALUES(\ (1114,1,2,125,9300)
INSERT INTO liniifact VALUES(\ (1115,1,2,100,9500)
INSERT INTO liniifact VALUES(\ (1116,2,1,150,6400)
INSERT INTO liniifact VALUES(\ (1117,1,2,35,10500)
INSERT INTO incasari VALUES(\ (1234,^2001/08/15],`OP`,`111`,^2000/08/10])
INSERT INTO incasari VALUES(\ (1235,^2001/08/15],`CHIT`,`222`,^2000/08/15])
INSERT INTO incasari VALUES(\ (1236,^2001/08/16],`OP`,`333`,^2000/08/09])
INSERT INTO incasari VALUES(\ (1237,^2001/08/17],`CEC`,`444`,^2000/08/10])
INSERT INTO incasari VALUES(\ (1238,^2001/08/17],`OP`,`555`,^2000/08/10])
INSERT INTO incasari VALUES(\ (1239,^2001/08/18],`OP`,`666`,^2000/08/11])
INSERT INTO incasfact VALUES(\ (1234,1111,5399625)
INSERT INTO incasfact VALUES(\ (1234,1118,5399625)
INSERT INTO incasfact VALUES(\ (1235,1112,5399625)
INSERT INTO incasfact VALUES(\ (1235,1117,5399625)
INSERT INTO incasfact VALUES(\ (1236,1118,5399625)
INSERT INTO incasfact VALUES(\ (1236,1120,5399625)
INSERT INTO incasfact VALUES(\ (1237,1117,5399625)
INSERT INTO incasfact VALUES(\ (1238,1113,5399625)
INSERT INTO incasfact VALUES(\ (1239,1117,5399625)
A'en'"e<<<
*D
(n exemplul de mai sus am pornit de la presupunerea ca in directoriul current exista cite un fisier grap)ic
cu extensia tif pentru fiecare produs4 iar ordinea acestora coiencide cu ordinea produselor din tabela4
ceea ce e destul de riscant. Astfel incit procedura ce urmeaza pare a fi una mai adecvata.
SELECT PRODUSE
SCAN
Nume_`figura_`+LTRIM(STR(codpr,6))+`.TIF`
IF FILE((nume_))
APPEND GENERAL image FROM (nume_) LINK
ENDIF
ENDSCAN
C. MODIFICAREA VALORILOR UNOR ATTRIBUTE
&pdates records in a table ,it) ne, values.
Syntax
UPDATE Da'aba,eName1<]TableName1
SET Col6mn>Name1 eE/%*e,,"on1
, Col6mn>Name2 eE/%*e,,"on2 ...]
WHERE F"l'e*Con#"'"on1 AND [ OR F"l'e*Con#"'"on2 ...]]
A*g6men',
5(ata-ase2ame3H6"a-le2ame3
Specifies the ta-le in which records are updated with new /alues.
(ata-ase2ame3H specifies the name of a non#current data-ase containing the ta-le. $ou must include
the name of the data-ase containing the ta-le if the data-ase is not the current one. &nclude the
exclamation point (H) delimiter after the data-ase name and -efore the ta-le name.
S" !olumnA2ame3 I expression3
5. !olumnA2ame: I expression:
Specifies the columns that are updated and their new /alues. &f you omit the 78* clause. e/ery row
in the column is updated with the same /alue.
78* Filter!ondition3 5)2( 4 1* Filter!ondition: ...66
Specifies the records that are updated with new /alues.
Filter!ondition specifies the criteria that records must meet to -e updated with new /alues. $ou can
include as many filter conditions as you li'e. connecting them with the )2( or 1* operator. $ou can
also use the 21" operator to re/erse the /alue of a logical expression. or use ,P"$( ) to chec' for an
empty field.
Rema*?,
0P()" # SQL can only update records in a single ta-le. 2ote that su-%ueries are supported in
0P()" D SQL.
0nli'e *PL)!. 0P()" # SQL uses record loc'ing when updating multiple records in a ta-le
opened for shared access. "his reduces record contention in multiuser situations. -ut may reduce
performance. For maximum performance. open the ta-le for exclusi/e use or use FL1!9( ) to loc' the
ta-le.
UPDATE 5 S1L Comman# E/am%le #"n HELP VFP
T(e =olloI"ng e/am%le o%en, '(e *+&#(me, 'able "n '(e #e&#1a#a #a'aba,e. UPDATE 5S1L ", 6,e# 'o
,e' all o= '(e Jal6e, "n '(e max(,1am# ="el# 'o 2:.
*>
CLOSE DATABASES
OPEN DATABASE (HOME(2 ! "Da#a$#e&#1a#a"
USE C+&#(me, %% Ope6 *+&#(me, #a)le
* Se# a61 10&pla7 am(+6#& -(, *+&#(me,&
UPDATE *+&#(me, SET max(,1am# 9 22
BRODSE FIELDS *(mpa67Fmax(,1am#
E/em%le +6 *e=e*"n'a la BD +*ea'a ma" ,6,
Remarca
Modificarea se produce pe toate liniile tabelei care indeplinesc conditia formulata prin
predicat.
De exemplu
No6l n6ma* #e 'ele=on al +l"en'6l6" +e a*e +o#6l 1KK1 e,'e K725717171. Sa ,e o%e*e8e
mo#"="+a*ea "n ba8a #e #a'e
UPDATE CLIENT;
SET telefon `032-313131`;
WHERE codcl1001
Modificarea cresterii TVA pentru toate produsele de la 0.19 la 0.22 se va efectua cu
ajutorul comenzii
UPDATE PRODUSE;
SET procTVA0.22;
:. INTERO3AREA BA;ELOR DE DATE @ COMANDA SELECT
Syntaxa
SELECT ALL [ DISTINCT] TOP nE/%* PERCENT]]
Al"a,.] Sele+'_I'em AS Col6mn>Name]
, Al"a,.] Sele+'_I'em AS Col6mn>Name] ...]
FROM FORCE]
Da'aba,eName!]Table AS] Lo+al>Al"a,]
INNER [ LEFT OUTER] [ RIGHT OUTER] [ FULL OUTER] 1OIN
Da'aba,eName!]Table AS] Lo+al>Al"a,]
ON Lo"nCon#"'"on .]
INTO De,'"na'"on]
[ TO FILE F"leName ADDITIVE] [ TO PRINTER PROMPT]
[ TO SCREEN]]
PREFERENCE P*e=e*en+eName]
NOCONSOLE]
PLAIN]
NOWAIT]
WHERE Lo"nCon#"'"on AND Lo"nCon#"'"on ...]
AND [ OR F"l'e*Con#"'"on AND [ OR F"l'e*Con#"'"on ...]]]
GROUP BY 3*o6%Col6mn , 3*o6%Col6mn ...]]
HAVING F"l'e*Con#"'"on]
UNION ALL] SELECTComman#]
ORDER BY O*#e*>I'em ASC [ DESC] , O*#e*>I'em ASC [ DESC] ...]]
*K
E/em%le #"n HELP VFP
SELECT - SQL Command Examples
#)e follo,ing examples illustrate t)e use of user-defined functions ,it) SE%E# - S8%Q
Example 1
Example * displa3s t)e names of all companies in customer -one field from one table..
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT customer.comany /
FROM customer
Example 2
Example 6 displa3s t)e contents of t)ree fields from t,o tables and +oins t)e t,o tables based on t)e
cust0%d field. (t uses local aliases for bot) tables.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT a.comany, b.order0date, b.s1%ed0on /
FROM customer a, orders b /
WHERE a.cust0%d = b.cust0%d
Example 3
Example ? displa3s onl3 records ,it) uniRue data in t)e specified fields.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT DISTINCT a.comany, b.order0date, b.s1%ed0on /
FROM customer a, orders b /
WHERE a.cust0%d = b.cust0%d
Example 4
Example G displa3s t)e country4 ostalcode, and comany fields in ascending order.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT country, ostalcode, comany /
FROM customer /
ORDER BY country, ostalcode, comany
Example 5
Example D stores t)e contents of fields from t,o tables in a t)ird table.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT a.comany, b.order0date, b.s1%ed0on /
FROM customer a, orders b /
WHERE a.cust0%d = b.cust0%d /
INTO TABLE custs1%.db!
&RO2SE
Example 6
Example > displa3s onl3 records ,it) an order date earlier t)an =6/*>/*FFG.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT a.comany, b.order0date, b.s1%ed0on /
FROM customer a, orders b /
WHERE a.cust0%d = b.cust0%d /
AND b.order0date 3 45166789*81:;
Example 7
Example K displa3s t)e names of all companies from customer ,it) a postal code t)at matc)es a postal
code in t)e orders table.
CLOSE ALL
CLOSE DATA&ASES
*J
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT comany FROM customer a WHERE /
EXISTS #SELECT < FROM orders b WHERE a.ostalcode = b.ostalcode$
Example 8
Example J displa3s all records from customer )aving a compan3 name t)at begins ,it) an uppercase
and is an unPno,n lengt).
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT < FROM customer a WHERE a.comany LIKE =C>=
Example 9
Example F displa3s all records from customer )aving a countr3 name t)at begins ,it) an uppercase &
and is follo,ed b3 one unPno,n c)aracter.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT < FROM customer a WHERE a.country LIKE =?0=
Example 10
Example *= displa3s t)e names of all cities in customer in uppercase and names t)e output column
C%tyL%st.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT ?''ER#c%ty$ AS C%tyL%st FROM customer
Example 11
Example ** demonstrates )o, 3ou can perform a Ruer3 on data t)at contains percentage signs -S.. A
bacPslas) -;. is placed before t)e percentage sign to indicate t)at it s)ould be treated as a literal4 and t)e
bacPslas) is specified as t)e escape c)aracter in t)e ESAPE clause.
Because t)e sample tables included ,it) Iisual /oxPro do not contain t)e percentage sign c)aracter4
t)is Ruer3 returns no results.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT < FROM customer/
2)ERE comany L@AE =>->>= ESCA'E =-=
Example 12
Example *6 demonstrates )o, 3ou can perform a Ruer3 on data t)at contains underscores -<.. A
bacPslas) -;. is placed before t)e underscore to indicate t)at it s)ould be treated as a literal4 and t)e
bacPslas) is specified as t)e escape c)aracter in t)e ESAPE clause.
Because t)e sample tables included ,it) Iisual /oxPro do not contain t)e underscore c)aracter4 t)is
Ruer3 returns no results.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT < FROM customer/
2)ERE comany L@AE =>-0>= ESCA'E =-=
Example 13
(n example *?4 t)e Escape c)aracter uses itself as a literal. #)e das) is bot) t)e escape c)aracter and a
literal. #)e Ruer3 returns all ro,s ,)ere t)e compan3 name contains a percentage sign follo,ed b3 a
das).
Because t)e sample tables included ,it) Iisual /oxPro do not contain t)e percentage sign c)aracter4
t)is Ruer3 returns no results.
CLOSE ALL
CLOSE DATA&ASES
O'E( DATA&ASE #)OME#*$ + ,data-testdata,$
SELECT < FROM customer/
2)ERE comany L@AE =>8>88>= Escae =8=
*F
Exemple cu referinta la Structura BD create in primul punct
E/em%le +6 *e=e*"n'a la BD +*ea'a ma" ,6,
omanda SE%E# respecta in IfP sintaxa de baza din standardul. S8%.F64 cele trei clauze principale
fiind SE%E#4 /$!M si L5E$E4 la care se adauga !$DE$ B24 0$!&P B24 5AI("0 si alte
elemente legate de subinterogari/subconsultari. De asemenea4 I/P utilizeaza si +onctiunea interna
(""E$ T!(" si extema !&#E$ T!(".
Exemplul 1
P*e,6%6n#n# +a %la'a ,e =a+e la 14 8"le) +a*e ,6n' =a+'6*"le +e 6*mea8a a =" "n+a,a'e "n %e*"oa#a 15-
18 a6g6,' 2001 ?
Solutia 1.1
SE%E# D(S#("# "r/act4 Data/act4 Data/act 9 *G AS Scadenta @
/$!M /acturi @
L5E$E Data/act 9 *G EA MN6==l/=J/*DO A"D @
Data/act9lG UA M:6==*/=J/*JO
Solutia l.2 - folosind propozitia BE#LEE"Q
SE%E# D(S#("# "r/act4 Data/act4 Data/act9 *G AS Scadenta @
/$!M /acturi@
L5E$E Data/act 9 *G BE#LEE" MN6==*/=J/*DO A"D M:6==*/=J/*JO
Exemplul 2
Ca*e ,6n' +l"enl"" #"n #"n Anen"" No" ," C*"6len"M
Solutia 2.1 :
SE%E# %(E"#(.7 @
/$!M %(E"#( (""E$ T!(" %!A%(#A#( @
!" %(E"#(.odPost A %!A%(#A#(.odPost @
L5E$E %ocAVAnenii "oiV !$ %ocAVriuleniV
Solutia 2.2- folosind operatorul ("Q
SE%E# %(E"#(.7 @
/$!M %(E"#( (""E$ T!(" %!A%(#A#( @
!" %(E"#(.odPost A %!A%(#A#(.odPost @
L5E$E %oc (" -BAnenii "oiB4 BriuleniB.
Solutia 2.3 -vec)ea sintaxa din S8%-JFQ
SE%E# %(E"#(.7 @
/$!M %(E"#(4 %!A%(#A#( @
L5E$E %(E"#(.odPost A %!A%(#A#(.odPost A"D %oc @
(" -BAnenii "oiB4 BriuleniB.
Solutia 2.4- sintaxa S8%-JF4 cu aliasuri pentru tabeleQ
6=
SE%E# .7 @
/$!M %(E"#( 4 %!A%(#A#( % @
L5E$E .odPost A %.odPost A"D @
%oc (" -BAnenii "oiB4 BriuleniB.
Solutia 2.5 - bazat pe subinterogari/subconsultari
SE%E# 7 @
/$!M %(.E"#( @
L5E$E odPost (" @
-SE%E# odPost @
/$!M %!A%(#A#( @
L5E$E %oc (" -BAnenii "oiB4 BriuleniB.@
.
Exemplul 3
Ce %e*,oane +(e"e '*eb6"e =el"+"'a'e #e S="n'6l IONM
Solutia 3.1 folosind operatorul %(1E
SE%E# dencl4 functie4 p.7@
/$!M persoane P (""E$ T!(" persclienti pc@
!" p.cnpApc.cnp@
(""E$ T!(" clienti c
!" pc.codclAc.codcl@
L5E$E &PPE$-Presume. %(1E W(!"XV !$@
&PPE$-Presume. %(1E W(!"XV !$@
&PPE$-Presume. %(1E WS (!"XV !$@
&PPE$-Presume. %(1E WS (!A"XV !$@
&PPE$-Presume. %(1E WS-(!"XV !$@
&PPE$-Presume. %(1E WS-(!A"XV
Exemplul 4
Ce %e*,oane +(e%e #e la ="*mele +l"en' 6n a6 e5ma"lM
Solutia 4.1 folosind operatorul (S "&%%
SE%E# dencl4 functie4 p.7@
/$!M persoane P (""E$ T!(" persclienti pc@
!" p.cnpApc.cnp@
(""E$ T!(" clienti c
!" pc.codclAc.codcl@
L5E$E email (S "&%%
Exemplul 5
Ca*e ,6n' =a+'6*"le em",e "n a+eea," 8" +a ," =a+'6*a 1117M
Solutia 5.1 bazata pe subinterogare/subconsultare
SE%E# 7@
/$!M facturi@
,)ere Data/act (" @
-SE%E# Data/act@
/$!M facturi@
L5E$E "r/actA***?.
Solutia 5.2 bazata pe +onctiunea interna
6*
SE%E# /*."r/act4 /*.Data/act@
/$!M facturi /* (""E$ T!(" facturi /6@
!" /*.Data/actA/6.Data/act A"D /6."r./actA***?
Solutia 5.3 folosind o interogare corelata
SE%E# 7@
/$!M facturi /*@
,)ere EH(S#S @
-SE%E# /*@
/$!M facturi /6@
L5E$E /*.Data/actA/6.Data/act A"D /6."r/actA***?.
Exemplul 6
Ca*e #"n'*e %e*,oanele #"n 'abela +6 a+ela," n6me 6n a6 =6n+'"" la ="*mele +l"en'M
Solutia 6.1 bazata pe subinterogare/subconsultare
SE%E# P.7@
/$!M persoane P@
,)ere cnp "!# (" @
-SE%E# "P@
/$!M persclienti.
Solutia 6.2 bazata pe +onctiunea externa
SE%E# 7@
/$!M persoane P %E/# !&#E$ T!(" persclienti P @
!" p.cnpApc.cnp@
L5E$E NVL-P.codcl4=.A=
Exemplul 7
/Functii agregat cu si fara grupare/
La +"'" +l"en'" ,a6 '*"m", =a+'6*"M
Solutia 7.1 bazata pe functia !&"# si o subinterogare/subconsultare
SE%E# !&"#-7.@
/$!M clienti@
,)ere codcl (" @
-SE%E# codcl@
/$!M facturi.
Solutia 7.2 bazata pe functia !&"# si clauza D(S#("#
SE%E# !&"#-D(S#("# codcl.@
/$!M facturi
Exemplul 8
Ca*e e,'e Jaloa*ea 'o'ala a =a+'6*"" 111N) Jaloa*ea me#"e) ma/"ma ," m"n"ma a %*o#6,elo* J"n#6'e %e
a+ea,'a =a+'6*aM
SE%E# S&M-cantitate7pretunit7-*9proc#IA. AS Ial<#otala@
AI0-cantitate7pretunit9 cantitate7pretunit7proc#IA. AS Ial<Medie@
M("-cantitate7pretunit9 cantitate7pretunit7proc#IA. AS Ial<Minima@
MAH-cantitate7pretunit9 cantitate7pretunit7proc#IA. AS Ial<Maxima@
66
$eturns a non-null value from t,o expressions.
Syntax
"I%-expression34 expression:.
Returns
)aracter4 Date4 Date#ime4 "umeric4 urrenc34
%ogical4 or t)e null value
Arguments
expression34 expression:
"I%- . returns expression: if expression3
evaluates to a null value. "I%- . returns
expression3 if expression3 is not a null value.
expression3 and expression: ma3 be an3 data
t3pe. "I%- . returns ."&%%. if bot)
expression3 and expression: bot) evaluate to
t)e null value.
/$!M produse P (""E$ T!(" linii /ac. %/@
!" P.codprA%/.codpr
Exemplul 9
!are este /aloarea totald a /inFdrilor pentru fiecare Fi in care s#au emis facturi Q
Pentru rezolvarea problemei este obligatorie folosirea gruparii
SE%E# Data/act4 S&M-antitate 7 Pret&nit 7 -l9Proc#IA.. AS Ial#otala @
/$!M %("((/A# %/4 P$!D&SE P4 /A#&$( / @
L5E$E %/.odPr A P.odPr A"D %/."r/act A /."r/act @
0$!&P B2 Data/act
Exemplul 10
Ca*e ,6n' J'"n8a*"le) +an'"'a'"J si Jalo*"+) %en'*6 ="e+a*e %*o#6, ?
SE%E# DenPr4 &M4 S&M-antitate. AS antitativ4 @
S&M-antitate 7 Pret&nit 7 -l9Proc#IA.. AS Ialoric @
/$!M %("((/A# %/4 P$!D&SE P4 /A#&$( / @
.L5E$E P.odPr A %/.odPr A"D %/."r/act A /."r/act @
0$!&P B2 DenPr4 &M
Exemplul ll
Sa ,e obl"na ,"'6al"a Jan8a*"lo* %e +l"enl" si 8"le) a=","n#65,e +a'e 6n ,6b'o'al la n"Jel , +l"en' si 6n 'o'al
gene*al.
Varianta propusa. reuneste multimea facturilor propriu#Fise. o-tinuta din prima fraFa SL!". cu
multimea su-totalurilor la ni/el de client (al doilea SL!") si cu o linie ce repreFint) totalul general.
SE%E# PAD$-A%%#-dencl.4G=. As Denumirelient4 @
datafact4@
S&M-antitate 7 Pret&nit 7 -l9Proc#IA.. AS Iinzari @
/$!M liniifact %/4 produse P4 facturi /4 clienti @
L5E$E p.codprA%/.codpr A"D %/."rfactA/."rfact@
A"D /.codclA.codcl@
0$!&P B2 dencl4 datafact@
UNION;
SE%E# PAD$-A%%#-dencl. 9V-SubtotalV4G=.4 M / / O4@
S&M-antitate 7 Pret&nit 7 -l9Proc#IA..@
/$!M liniifact %/4 produse P4 facturi /4 clienti @
L5E$E p.codprA%/.codpr A"D %/."rfactA/."rfact@
A"D /.codclA.codcl@
0$!&P B2 dencl4 datafact@
UNION;
SE%E# 5$-6DD.9V#otal 0eneralV4 M / / O4@
S&M-antitate 7 Pret&nit 7 -l9Proc#IA..@
/$!M liniifact %/4 produse P@
L5E$E p.codprA%/.codpr
Exemplul 12
Ca*e ,6n' 8"lele "n +a*e ,a6 "n'o+m"' +el %6'"n 7 =a+'6*"?
SE%E# datafact4 !&"#-7. AS "r</acturi@
/$!M facturi@
6?
0$!&P B2 datafact@
5AI("0 !&"#-7.EA?
Exemplul 13
&n ce File s#au /andut si produsul cu denumirea JProdus * : si cel cu denumir JProdus 6: Y
Desi are un enunt banal4 rezolvarea acestei probleme ofera oportunitatea unor interogari dintre cele mai
spumoase. Ia prezentam numai cinci dintre acestea.
.Solutia 13.1.- +onctionarea unei instante obtinuta prin +onctiunea P$!D&SE-%("((/A#-/A#&$(
-(n care DenPr A BProdus * B. cu o alta instanta aceleiasi combinatii -(n care DenPr A BProdus 6B.Q
SE%E# D(S#("# /l.DataEact @
/$!M P$!D&SE Pl @
(""E$ T!(" %("((/A# %/*@
!" Pl.odPr A %/*.odPr @
(""E$ T!(" /A#&$( /l @
!" %/*."r/act A /l."r/act @
(""E$ T!(" /A#&$( /6@
!" /l.DatafactA/64Data/act @
(""E$ T!(" %("((/A# %/6@
!" %/6.."rfactA /6."r/act @
(""E$ T!(" P$!D&SE P6@
!"%/6.odPr A P6.odPr @
L5E$E Pl.Denpr A BProdus lB A"D P6.DenPr A BProdus 6B
.Solutia 13.2- folosind clauza 5AI("0 si functia !&"#Q
SE%E# D(S#("# Data/act @
/$!M P$!D&SE (""E$ T!(" %("((/A# @
!" P$!D&SE. odPr A %("((/A#. odPr @
(""E$ T!(" /A#&$( @
!" %("((/A#."rfact A/A#&$(."rfact@
L5E$E DenPr@
(" -BProdus lB4VProdus 6B. (@
0$!&P B2 Data/act @
5AI("0 !&"#-D(S#("# %("((/A#.odPr. A 6
Solutia 13.3- simuland intersectia prin subconsultariQ
SE%E# D(S#("# Data/act @
/$!M P$!D&SE (""E$ T!(" %(."((/A# @
!" P$!D&SE.odPr A %("((/A#.odPr @
(""E$ T!(" /A#&$(
!" %("((/A#."rfact A /A#&$."r/act
L5E$E DenPr A BProdus lB A"D Data/act (" @
-SE%E# D(S#("# Data/act @
/$!M P$!D&SE @
(""E$ T!(" %("((/A#@
!" P$!D&SE.odP$ A %("((/A#.odPr @
(""E$ T!(" /A#&$(@
!" %("((/A#."rfact A /A#&$(."r/act @
6G
L5E$E DenPr A BProdus 6B.
Solutia 13.4 -prin corelarea a doua instante ale +onctiunii P$!D&SE-%("((/A# - /A#&$(@ prima
contine liniile legate de Produs &. iar a doua de Produs 6Q
SE%E# D(S#("# Data/act @
/$!M P$!D&SE Pl4 %("((/A# %/*4 /A#!$( /l @
L5E$E Pl.odPr A %/*.odPr A"D @
%/*."ffact I/*."r/act A"D DenPr A WProdus * B @
A"D EH(S#S@
-SE%E# *@
/$!M P$!D&SE P64 %("((/A# %/64 /A#&E( /6 @
L5E$E P6.odPr A %/6.odPr A"D %f6@"rfact A /6."r/act@
A"D P6.DenprA BProdus 6B A"D /6.Data/actA/l.Data/act.
Solutia 13.5Q
SE%E# D(S#("# Data/act @
/$!M /A#&$( @
(""E$ T!(" %("((/A#
!" /A#&$(."r/actA%("((/A#."r/act @
(""E$ T!(" P$!P&SE
!" %(."((/A#.odPrAP$!D&SE.odPr A"D DenPr (" -BProdus .*B4 BProdus 6B. @
L5E$E D#!-Data/act.9D#!-M / / O. "!# (" @
-SE%E# D(S#("# @
D#!-/*.Data/act.9D#!-"I%-/6.Data/act4M / / O.. @
/$!M /A#&$( /l (""E$ T!(" P$!D&SE P* @
!" P*.DenPr (" -BProdus *B4 BProdus 6B. @
%E/# !&#E$ T!(" -%("(.(/A# %/6 (""E$ T!(" /A#&$( /6 @
Z" %/6 ."r/actQ/6 ."r/at .
!" /*. Data/actA/6 .Data/act A"D P*.odPrA%/6 .odPr.
Exemplul 14
A=",a*ea %e +oloane ,e%a*a'e) %en'*6 +ele '*e" ge,'"6n") a =a+'6*"lo* ne+e,"'a =olo,"*ea 6ne" ,e+Jen'e #e
IF56*" "mme#"a'e !IIF56*"-O
SE%E# ((/-gestiune A B==*B4 S#$-/."r/act4J.4 spaceMJ.. @
AS 0estiune ==*4 @
((/-gestiune AB==6V4 S#$M/."r/act4J.4 spaceMJ.. @
AS 0estiune ==64 @
((/-gestiune AB==?V4 S#$M/."r/act4J.4 spaceMJ.. @
AS 0estiune ==?4 @
Data/act4 S&M-antitate 7 Pret&nit 7 -l9Proc#IA.. @
AS Ial#otala @
/$!M /A#&$( / @
(""E$ T!(" %("((/A# %/
!" /."r/act A %/."r/act @
(""E$ T!(" P$!D&SE P
!" %/.odPr A P.odPr @
0$!&P B2 /."r/act
Exemplul 15
6D
S+a#enla ="e+a*e" =a+'6*" em",e e,'e #e 20 #e 8"le. Da+a "n,a #a'a5l"m"'a +a#e "n'*5o ,amba'a ,a6
#6m"n"+a) a'6n+" ,+a#enla ,e m6'a "n l6nea 6*ma'oa*e. Ca*e ,6n' 8"lele) ,+a#en'e "n a+e,'e +on#"l"" ?
Iisual /oxPro prezinta functiile D!L (!haracter (ay 1f the 7ee') si D!L ((ay of the 7ee').&n
acest caF putem o-tine urmatorul reFultat.
SE%E# "r/act AS /actura4 Data/act4 @
Data/act 9 6= AS Scadental4 @
D!L-Data/act96=. AS "ume'il4 @
((/-D!L-Data/act96=.A>4 @
Data/act9664 @
((/-D!L-Data/act96=.A*4 @
Data/act96*4 @
Data/act96=. . AS Scadenta4@
D!L-((/-D!L-Datafact96=.A>4@
Data/act9664 @
((/-D!L-Data/act96=.A*4 @
Data/act96*4@
Data/act96=. . . AS '(<Scadenta @
/$!M /A#&$(
Exemplul 16
Ca*e ,6n' Jalo*"le =a+'6*a'e ," "n+a,a'e ale ="e+""*e" =a+'6*" ?
Solutia de mai +os4 reune[te facturile care au macar o transa de incasare cu cele nelncasate delocQ
SE%E# /. "r/act4 @
S&M-antitate 7Pfret&nit 7 -l9Proc#IA... / @
!&"# -D(S#("# (..od(nc. AS /acturat4 @
S&M-#ransa. / MAH-%/.%inie. AS (ncasat @
/$!M %("((/A# %/4 P$!D&SE P4 /A#&$( /4 ("AS/A# ( @
L5E$E %/.odPr A P.odPr A"D %/."r/act A /."r/act @
A"D /."r/actA(."r/act @
0$!&P B2 /."r/act @
UNION ;
SE%E# /. "r/act4 @
S&M-antitate 7 P9Pret&pit 7 -l9Proc#IA.. AS /acturat4
= AS (ncasat @
/$!M %("((/A# %/4 P$!D&SE P4 /A#&$( / @
L5E$E %/.odPr A P.odPr A"D %/."r/act A /."r/act @
A"D /."r/act "!# (" @
-SE%E# "r/act @
/B$!M ("AS/A#. @
0$!&P B2 /."r/act
Cla68a TOP. O%e*a'o*"" ALL ," )2$ (S1,)
Exemplul 17
Ca*e ,6n' +ele ma" ma*" +"n+" %*el6*" 6n"'a*e #e Jan8a*e) %*o#6,ele ," =a+'6*"le "n +a*e a%a* +ele +"n+"
%*el6*" ma/"meM
(n alte S0BD-uri4 aceasta problema ar crea mari dureri de cap. lauza #!P din I/P realizeaza
ordonarea si extragerea celor cinci valori relative simplu .
6>
SE%E# #8P D "r/act4 DenPr4 Pret&nit @
/$!M %("((/A# (""E$ T!(" P$!D&SE @
!" %("((/A#.odPrAP$!D&SE.odPr@
!$DE$ B2 Pret&nit DES
Exemplul 18
Ca*e ,6n' %*o#6,ele Jan#6'e la %*e'6*" 6n"'a*e ,6%e*"oa*e o*"+a*6" %*e' 6n"'a* la +a*ea =o,' Jan#6'
PP*o#6, IP ?
&nul dintre obiectivele acestui exemplu este de a prezenta modul de conexiune a unei consultari cu
subconsultarea sa prin operatorul A%%.
SE%E# D(S#("# DenPr4 Pret&nit @
/$!M P$!D&SE P4 %("((/A# %/ @
L5E$E p.odPrA%/.o8P A"D Pretunit E A%% @
-SE%E# D(S#("# Pret&nit@
/$!M P$!D&SE P4 %("((/A# %/@
L5E$E p.odPrA%/.odPr A"D DenPr ABProdus *B
Exemplul 19
Ca*e ,6n' %*o#6,ele Jan#6'e la %*el6*" 6n"'a*e ,6%e*"oa*e ma+a* 6n6" %*el 6n"'a* al PP*o#6,6l6" lP M
Este genul de situatii in care se foloseste S!ME sau A"2 -au aceeasi functiune..
SE%E# D(S#("# DenPr4 Pret&nit @
/$!M $!D&SE P (""E$ T!*" %("((/A# %/ 4
!" P.odPrA%/.odPr @
L5E$E Pret&nit E A"2@
-SE%E# D(S#("# Pret&nit @
/$!M P$!D&SE P (""E$ T!(" %("((/A#
!" P.odPrA%/.odPr @
L5E$E DenPr ABProdus *B.
Exemplul 20
Ca*e e,'e 6l'"ma =a+'6*a "n'o+m"'a A=a+'6*a +ea ma" *e+en'aA ," #a'a "n +a*e a =o,' *em",a M
Aceasta este o problema cu multe variante de rezolvare
Solutie 20.1
SE%E# Data/act4 "r/act AS &ltima</actura @
/$!M facturi@
L5E$E "r/act ("@
-SE%E# MAH-"rfact.@
/$!M facturi.
Solutie 20.2 in locul operatorului de conexiune (" este utilizat semnul A
SE%E# Data/act4 "r/act AS &ltima</actura @
/$!M facturi@
L5E$E "r/act A@
-SE%E# MAH-"rfact.@
/$!M facturi.
Solutie 20.3 in locul operatorului de conexiune (" este utilizat operatorul A"2
6K
SE%E# Data/act4 "r/act AS &ltima</actura @
/$!M facturi@
L5E$E "r/act A A"2@
-SE%E# MAH-"rfact.@
/$!M facturi.
Solutie 20.4 in locul operatorului de conexiune (" este utilizat operatorul A%%
SE%E# Data/act4 "r/act AS &ltima</actura @
/$!M facturi@
L5E$E "r/act A A%%@
-SE%E# MAH-"rfact.@
/$!M facturi.
Solutie 20.5 in locul operatorului de conexiune (" este utilizat operatorul EAA%%
SE%E# Data/act4 "r/act AS &ltima</actura @
/$!M facturi@
L5E$E "r/act A A%%@
-SE%E# "rfact@
/$!M facturi.
Solutie 20.6 Se utilizeaza clauza #!P
SE%E# #!P * Data/act4 !&"#-7. AS "r @
/$!M facturi@
0$!&P B2 Data/act@
!$DE$ B2 "r DES
Exemplul 21
Ca*e e,'e ge,'"6nea +6 J"n8a*"le +ele ma" b6ne ?
Daca in alte S0BD-uri sunt necesare subconsultari in clauza /$!M4 in I/P4 aceasi clauza #!P
salveaza totulC
SE%E# #!P * 0estiune4 S&M-antitate 7 Pret&nit 7 -l9Proc#IA.. AS Iinzari<0estiuni @
/$!M /A#&$( / @
(""E$ T!(" %("((/A# %/
!" /."r/actA%/."r/act @
(""E$ T!(" P$!D&SE P
!" %/.odPrAP.odPr @
0$!&P B2 0estiune @
!DE$ B2 Iinzari<0estiuni DES
Q. In+l6#e*ea +omen8"" SELECT "n %*og*ame
Multe din necesitatile I/P necesita folosirea in S8% a mai multor nivele de subconsultare in mod
deosebit in propozitiile /$!M sau 5AI("0. Aceste facilitate nucleul S8% in I/P nu le are in deplina
masura si putere.
(n sc)im in I/P aceste rezultate se pot crea ca rezultate intermediare stocate in &$S!A$E sau
#ABE%E virtuale care la rindul lor pot fi utilizate ca argumente in alte noi consultari.
SalJa*ea 6ne" o%e*a'"" SELECT "n'*56n CURSOR
6J

&$S!$&% este in I/P o tabelea temporara care exista din momentul formarii comenzii SE%E# cu
clauza ("#! &$S!$ sau $EA#E &$S!$ si pina la includerea sa implicita sau explicita
Sa revenim la Exemplul 13.
&n ce File sau /indut si produsul cu denumirea Produs 3 si produsul cu denumirea Produs :
%a seria interogarilor care au fost prezentate de+a mai adaugam si o varianta simpla de program dupa
cum urmeaza
P*og*ame VFP +e ,alJea8a *e86l'a'ele "n'e*me#"a*e ale "n'e*oga*"lo* "n +6*,oa*e
SE%E# D(S#("# Data/act @
("#! &$S!$ 'ile<P* @
/$!M P$!D&SE (""E$ T!(" %("((/A# !" P$!D&SE.odPr A %("((/A#.odPr @
(""E$ T!(" /A#&$( !" %("((/A#."rfact A /A#&$(."r/act @
L5E$E DenPr A BProdus lB
SE%E# D(S#("# Data/act @
("#! &$S!$ 'ile<P6 @
/$!M P$!D&SE (""E$ T!(" %l"((/A# !" P$!D&SE.odPr A %l"((/A#.odPr @
(""E$ T!(" /A#&$( !" %l"((/A#."rfact A /A#&$(."r/act @
L5E$E DenPr A BProdus 6B
SE%E# 7@
/$!M 'ile<P*
L5E$E Data/act ("
-SE%E# Data/act@
/$!M '(%E<P6.
Prima interogare creaza cursoul 'ile<P* si contine numai zilele in care s-a vindut primul produs.
'ile<P6 este cursorul ce tine de zilele cind s-a vindut al doilea produs.
&ltima interogare contine intersectia celor doua cursoare ce rezolva problema
E/em%l6l 22
Ca*e e,'e *a"on6l +6 J"n8a*" "me#"a' ,6%e*"oa*e *a"on6l6" Anen"" No" M
(nteresul este aici ca in L5E$E are loc +onctiunea care solutioneaza cazul
7777 Iinzarile raionului Anenii "oi
SE%E# S&M-antitate 7 Pret&nit 7 -* 9Proc#IA.. AS Iinzari @
/$!M raioane $ @
(""E$ T!(" %!A%(#A#( % !" $.nraiA%.nrai @
(""E$ T!(" %(E"#( !" %.odPostA.odPost @
(""E$ T!(" /A#&$( / !" .od(A/.od( @
(""E$ T!(" %("((/A# %/ !" /."r/actA%/."r/act @
(""E$ T!(" P$!D&SE P !" %/.odPrAP.odPr @
("#! &$S!$ cIinzari<Aneni<"oi L5E$E raionABAnenii "oiB
7777 Iinzarile f+ecarui raion
SE%E# raion4 S&M-antitate .Pret&nit .-*9Proc#IA.. AS Iinzari @
/$!M raioane $ @
(""E$ T!(" %!A%(#A#( % !" $.nraiA%.nrai @
6F
(""E$ T!(" %(E"#( !" %.odPostA.odPost @
(""E$ T!(" /A#&$( / !" .od(A/.od( @
(""E$ T!(" %l"((/A# %/ !" /."r/actA%/."r/act @
(""E$ T!(" P$!D&SE P !" %/.odPrAP.odPr @
("#! &$S!$ cIinzari<$aioane 0$!&P B2 raion
SE%E# raion4 Iinzari @
/$!M cIinzari<$aioane@
L5E$E Iinzari UA A%% @
-SE%E# cIinzari<$aioane.Iinzari @
/$!M cIinzari<$aioane4 cIinzari<Anenii<"oi @
L5E$E cIinzari<$aioane.Iinzari E cIinzari<Anenii<"oi.Iinzari. @
A"D Iinzari E A%% @
-SE%E# Iinzari @
/$!M cIinzari<Anenii<"oi.
R. Al'e +on,"#e*a'"" %*"J"n# +6*,oa*ele
&n cursor poate ti creat si prin comanda $EA#E &$S!$4 caz in care tabela temporara este
actualizabila. /ormatul comenzii prezinta clauze similare $E
Syntaxa
$EA#E &$S!$ aliasAname
-fname3 type \-precision \4 scaleZ.
\"&%% ] "!# "&%%Z
\5E1 lxpression \E$$!$ c,essage"extZZ
\DE/A&%# expressionZ
\&"(8&EZ
\"!P#$A"SZZ
\4 fname: ...Z.
] /$!M A$$A2 )rray2ame
Din 5E%P I/P
"he following example creates a cursor with the alias emloyee. ) -lan' record is appended. filled. and displayed with the
+*17S command.
CLOSE DATABASES
CLEAR
CREATE CURSOR emloyee "
#Em$D ,#A&+ ,ame C#-.&+ Address C#2.&+ City C#2.&+ "
'ostalCode C#1.&+ Office,o C#B& ,0LL+ Secialty (&
D$S'LA) STR0CT0RE
CA$T C$,DOC 8'ress a !ey to add a record/8
$,SERT $,TO emloyee #Em$d+ ,ame+ Address+ City+ 'ostalCode+ "
Office,o+ Secialty&"
?AL0ES #1..-+ 8Dr/ Bonnie Doren8+ 80ni;ersity of Ore<on8+ 8Eu<ene8+ "
87B5.28+ 88+ 8Secondary Secial Education8&
BROCSE
* At this oint you could coy this record to a ermanent table
CLOSE ALL 44 Once the cursor is closed+ all data is flushed
44 from memory
CLEAR
?=
! data creat si declarate restrictiile4 un cursor poate fi actualizat ca orice tabela obisnuita4 prin comenzile
S8%Q ("SE$#4 &PDA#E si DE%E#E4 precum si orice alta comanda de editare specifica I/P. De
asemenea4 orice incalcare a vreunei restrictii definite va fi sernnalizata. ursoarelor4 similar tabelelor
virtuale4 li se pot vizualiza si configura proprietatile prin functiile &$S!$0E#P$!P- . si
&$S!$SE#P$8P-..
ontinutul unui cursor poate fi adaugat la inregistrarile curente ale unei tabele prin comanda
APPEND FROM DBF ( '<NumeCursor>' ) .
ursoarele pot fi4 in unele cazuri un bun inlocuitor al vectorilor.
Exemplu. Este stiut ca agentilor care ac)ita bine platile si impozitele li se acorda anumite facilitati4 de
exemplu anumite reduceri la plati.
P*og*am #e +al+6l al *e#6+e*"lo* a+o*#a'e %en'*6 "n+a,a*" ," an6me %en'*6 '*an,ele #e =a+'6*"
%la'"'e AINCASARI.Da'aIn+A
"n 'e*men #e %"na la 1K 8"le ,e a+o*#a o *e#6+e*e #e 1KS
"n'*e 11 ," 12 8"le ,e a+o*#a o *e#6+e*e #e NS
"n'*e 17 ," 1: 8"le ,e a+o*#a o *e#6+e*e #e TS
%e,'e 1Q 8"le n6 ,e a+o*#a n"+" o =aJao*e A"n *eal"'a'e ,e a+o*#a %enal"8a*"A
#ransele acordate a reducerilor pot fi stocate in cursoare si astfel folosite la interogari.
` se creaza si introduce datele in cursorul cu transele de reduceri
$EA#E &$S!$ transe<red - @
zile<min ("#E0E$4 @
zile<max ("#E0E$4 @
procent ("#E0E$ @
.
("SE$# ("#! transe<red IA%&ES - =4 *=4 *=.
("SE$# ("#! transe<red IA%&ES -**4 *64 F.
("SE$# ("#! transe<red IA%&ES -*?4 *D4 J.
("SE$# ("#! transe<red IA%&ES -*>4FFFFF4 =.
`pentru fiecare factura cu valoare peste zero se insereaza
`in cursorul FACT_TRANSE cite o linie pentru fiecare transa
`posibila de reduceri
SE%E# "r/act4 Data/act4 Ial#otala4 Data/act 9 zile<min AS %iminf4
Data/act 9 zile<max AS %imSup4 procent @
/$!M /A#&$(4 #$A"SE<$ED
("#! &$S!$ /A#<#$A"SE @
L5E$E procent E = A"D Ial#otala E =
` se calculeaza reducerile pe fiecare transa
SE%E# /A#<#$A"SE.74 Datalnc4 #ransa4 ("#-Procent 7 #ransa **==. AS $educere @
("#! &$S!$ reduceri<transe @
/$!M ("AS/A# (""E$ T!(" ("ASA$( !" ("AS/A#.odlncA("ASA$(.odlnc @
(""E$ T!(" /A#<#$A"SE @
!" ("AS/A#."r/act A /A#<#$A"SE."r/act @
L5E$E ("ASA$(.Datainc EA /A#<#$A"SE.%iminf A"D @
("ASA$(.Datainc UA /A#<#$A"SE.%imSup
7 se actualizeaza atributul /A#&$(.$educeri
?*
D(ME suma<-*4 *.
SE%E# facturi
SA"
Suma< A =
SE%E# S&M-$educere. @
("#! A$$A2 suma<@
/$!M $ED&E$(- #$A"SE @
L5E$E "r/act A facturi."rfact
SE%E# facturi
$EP%AE $educeri L(#5 suma<-* 4 * .
E"DSA"
Este o solutie nu prea simpla dar operationalaCCC Aici pielea costa cit dubalaC
T. Va*"an'e %en'*6 6'"l"8a*ea "n'e*oga*"lo*
Exemplu.
De listat facturile emise catre un client pentru un anumit interval de timp definit de o data initiala si una
finala.
Programul ce urmeaza este o procedura si la ea se poate de adresat cu parametri
PROCEDURE listare
PARAMETER codcl_, datainf_,datasup_
SELECT DenCI AS Client, Nrfact, DataFact, Gestiune, ValTotala AS Valoare;
FROM clienti C LEFT OUTER 1OIN facturi F
ON C.codclF.codcl;
WHERE F.codclcodcl_ AND datafact BETWEEN datainf_ AND datasup_
RETURN
ENDPROC
Pentru a obtine lista clientului * /cod *==*/ in perioada 6-K august 6==* apelam la procedura scrisa dupa
cum urmeaza
DO listare WITH 1001,^2001/08/02],^2001/08/07]
Iarianta ce urmeaza permite afisarea pe ecran
PROCEDURE listare
PARAMETER codcl_, datainf_,datasup_
SELECT DenCI AS Client, Nrfact, DataFact, Gestiune, ValTotala AS Valoare;
INTO CURSOR c1 @
FROM clienti C LEFT OUTER 1OIN facturi F
ON C.codclF.codcl;
WHERE F.codclcodcl_ AND datafact BETWEEN datainf_ AND datasup_
Titlu_`Lista facturilor pentru clientul`+ALLTRIM(c1.client)+`in perioada`+ ;
DTOC(datainf_)+`-+DTOC(datasup_)
SELECT C1
BROWSE TITLE Titlu_
RETURN
ENDPROC
(mportant este ca in asa mod obtinem rezultatele fara a incarca memoria cu ^0unoi_ adica tabele in plus
?6
N. Ma+*o,6b,'"'6'"a "n =*a8e SELECT
Sa presupunem ca o aceeasi lista - a facturilor ce contine urmatoarele dateQ
- numarul facturii4
- data emiterii4
- numele clientului4
- local+tatea in care-si are sediul c*ientul4
- valoarea incasata pana in momentul curent -
trebuie obtinuta pentru un anumit interval calendaristic4 in orice ordine declarata prin toate combinatiile
posibile ale celor cinci cimpuri
Ia'a o Ja*"an'a #e %*og*am
PROCEDURE listare1
PARAMETER datainf_,datasup_,cimp1_,cimp2_,cimp3_,cimp4_
SELECT Dencl AS Client, Loc As Localitate, Nrfact, DataFact, Gestiune, ValTotala AS Valoare;
FROM clienti C LEFT OUTER 1OIN facturi F
ON C.codclF.codcl;
INNER 1OIN LOCALITATI %
ON C.CodPost A L.CodPost;
WHERE Datafact BETWEEN datainf_ AND datasup_ @
ORDER BY &cimp1, &cimp2_, &cimp3_, &cimp4_
RETURN
ENDPROC
lauza !$DE$ B2 se construieste dinamic cu a+utorul macrosubstitutiei.
%ansarea acestui program se face cu comanda D!Q
D! listare* L(#5 MN6==*/=J/=6O4 MN6==*/=J/=KO4 B%ocB4 BData/actB4 BDenlB4 BIal#otalaB
(n continuare se propune o varianta mai eleganta.
e-ar fi ca4 in arara celor doua date calendaristice4 de inceput si de sfarsit4 ordonarea sa fie precizata
printr-o lista care sa contina unul4 doua4 trei. ..sau c)iar nici un atributY
Programul ce urmeaza preia un parametru de tip sir de caractere care este4 de rapt4 lista atributelor de
ordonare4 atribute separate prin virgula.
Asa incat programul analizeaza virgulele din sir si extrage atributele pe baza carora se va construi4
dinamic4 clauza L5E$E.
In e/em%l6l +e 6*mea8a ,e %*e"a n6ma" #a'a "n"'"ala ," ="nala) %l6, o*#"nea #e %*e8en'a*e) ,6b =o*ma
#e l",'a #e a'*"b6'e ,e%a*a'e %*"n J"*g6la
$eturns t)e beginning numeric position of t)e first occurrence of a c)aracter expression or memo field
,it)in anot)er c)aracter expression or memo field, counting from t)e leftmost c)aracter. %a inceput sa
facem cunostinta cu functia AT()
S$n'a/a
)"(cSearchxpression. cxpressionSearched 5. n1ccurrence6)
Re'6*n,
2umeric
A*g6men',
cSearchxpression
Specifies the character expression that )"( ) searches for in cxpressionSearched.
??
cxpressionSearched
Specifies the character expression cSearchxpression searches for.
+oth cSearchxpression and cxpressionSearched can -e memo fields of any siFe.
n1ccurrence
Specifies which occurrence (first. second. third. and so on) of cSearchxpression is searched for in
cxpressionSearched. +y default. )"( ) searches for the first occurrence of cSearchxpression
(n1ccurrence I 3). &ncluding n1ccurrence lets you search for additional occurrences of
cSearchxpression in cxpressionSearched. )"( ) returns K if n1ccurrence is greater than the num-er
of times cSearchxpression occurs in cxpressionSearched.
Rema*?,
)"( ) searches the second character expression for the first occurrence of the first character expression.
&t then returns an integer indicating the position of the first character in the character expression found.
&f the character expression isnBt found. )"( ) returns K.
"he search performed -y )"( ) is case#sensiti/e. "o perform a search that isnBt case#sensiti/e. use
)"!( ).
PROCEDURE listare2
PARAMETER datainf_, datasup_, ordinea_
I1
7se determina prima pozitie a virgulei -asta inseamna cu sunt macar
7doua atribute de ordonare.
poz_ A AT -B4B4 ordinea_, i.
IF poz_ E = XX exista macar o virgula4 deci sunt mai multe atribute de ordonare
7 se localizeaza toate virgulele si se extrag atributele cuprinse intre virgule
poz_preced A !
DO WHILE poz_ ` !
ii A str(i,1)
cimp&ii A SUBSTR(ordinea_, poz_preced 9 *4 poz_ -poz_preced -* .
poz_preced A poz_
i i+ 1
poz_ A AT -B4B4 ordinea_, i)
ENDDO
7a mai ramas atributul dintre ultima virgula si sfirsitul sirului de ordonare
ii A str(i,1)
cimp&ii A SUBSTR(ordinea_, poz_preced 9 *4 LEN(ordinea_) -poz_preced)
7se construieste clauza !$DE$ B2
order_by_ A W V
FOR + A * TO i
jj A STR(j,1)
IF + E *
order_by_ A order_by_ 9 ,`
ENDIF
order_by_ A order_by_ 9 ALLTRIM(cimp&jj)
ENDFOR
?G
ELSE XX exista maximum un atribut de ordonare de la (/ poz<E=
(/ %E"-A%%#-ordinea<..A= XX de fapt4 nu exista nici un atribut de ordonare
!rder<b3<AV*V XX ordonarea se face dupa prima coloana
E%SE
!rder<b3<AA%%#$(M-ordinea<. XX exista un singur atribut de ordonare
E"D(/
E"D(/
7 si acum presentam propriu zis ordonarea
SELECT Dencl AS Client, Loc As Localitate, Nrfact, DataFact, Gestiune, ValTotala AS Valoare;
FROM clienti C LEFT OUTER 1OIN facturi F
ON C.codclF.codcl;
INNER 1OIN LOCALITATI %
ON C.CodPost A L.CodPost;
WHERE Datafact BETWEEN datainf_ AND datasup_ @
ORDER BY &order_by_
RETURN
ENDPROC
Prezentam ? moduri de adresare la programul prezentat mai sus
DO listare2 WITH ^2001/08/02], ^2001/08/07], 'ValTotala,Dencl,NrFact'
DO listare2 WITH ^2001/08/02], ^2001/08/07], 'NrFact'
DO listare2 WITH ^2001/08/02], ^2001/08/07], ' '
1K. Ma+*o,6b,'"'6'"e ," "'e*a'"" S1L
#ot cu a+utorul macrosubstitutiei se pot rezolva situatii dintre cele mai dificile de obtinere a unor
rapoarte pretentioase. Spre exemplificare4 dorim obtinerea unui raport matriceal in care4 pe verticala4 sa
fie prezente toate produsele comercializate de firma4 iar :ordonata: sa fie constituita dfn primele patru
zile ale lunii august 6==*4 adica
DenPr odPr 'i =* =J 6==* 'i =6 =J 6==* 'i =? =J 6==* 'i =G =J 6==*
Pentru facilitarea prezentarii4 sa ne limitam la patru zile4 dar programul ce urmeaza functioneaza pentru
oricate zile dorim4 singura problema fiind completarea cursorului '(%E.
(n prograrnul ce urmeaza4 aceasta se face prin ("SE$#-uri directe4 insa in aplicatii datele initiale si
finale ale intervalului se pot prelua printr-un formular si4 astfel4 completarea cursorului se
automatizeaza.
SET MARK TO '_' XX separatorul pentru data calendaristica
CREATE CURSOR Zile (Zi DATE)
INSERT INTO Zile VALUES (^2001/08/01])
INSERT INTO Zile VALUES (^2001/08/02])
INSERT INTO Zile VALUES ((^2001/08/03])
INSERT INTO Zile VALUES (^2001/08/04])
?D
SELECT DataFact, DenPr, LF.CodPr, SUM(INT(Cantitate .PretUnit .(1+ProcTVA))) AS
Valoare;
INTO CURSOR Zile_Produse ;
FROM FACTURI F INNER 1OIN LINIIFACT LF ON F.NrFact LF.NrFact ;
INNER 1OIN PRODUSE P ON LF.CodPrP.CodPr ;
WHERE DataFact IN ;
-SE%E# 'i @
/$!M 'ile. @
0$!&P B2 Data/act4 DenPr4 %/.odPr
SELECT DenPr, CodPr;
INTO CURSOR c1 @
FROM PRODUSE @
ORDER BY DenPr
i *
SELECT Zile
SCAN
ii A ALL T(STR(i,2))
ii_plus_1 A ALL T(STR(i+1 46..
ziua_A '_'+DTOC(Zile.Zi)
SELECT cXii..74 NVL(ZILE_PRODUSE.Valoare,0) AS Zi&ziua_ @
FROM c&ii LEFT OUTER 1OIN ZILE_PRODUSE @
ON c&ii..CodPr A ZILE_PRODUSE.CodPr AND DataFact A Zile.Zi ;
INTO CURSOR c&ii_plus_1
ii+ *
SELECT Zile
E"DSA"
SELECT cXii<plus<*
BROWSE TITLE BIinzari<Produse/'ileB
SELECT 'ile
USE
SELECT 'ile<Produse
USE
FOR j1 TO i
ii ALLT(STR(j,2))
SELECT c&ii
USE
ENDFOR
ateva explicatii. ursorul '(%E contine toate datele calendaristice care trebuie sa apara drept coloane
ale raportului.
Ialorile vanzarilor pe produse si zile sunt calculate si stocate in cursorul ' (%E<P$!D&SE.
%iniile raportului sunt alcatuite din toate produsele firmei4 astfel incat cursorul :de start: - * -este
obtinut din tabela P$!D&SE.
"umarul iteratiilor depinde de numarul inregistrarilor din cursorul '(%E - numarul zilelor pentru care
intereseaza raportul.
?>
orpul ciclului contine +onctiunea cursorului :curent: cu ziua corespunzatoare inregistrarii curente din
cursorul '(%E.
?K

Vous aimerez peut-être aussi