Vous êtes sur la page 1sur 38

9/3/12

SQL Examples

SQL EXAMPLES WITH MICROSOFT'S SQL SERVER


1. Working with Databases
A. Creating Databases:

CREATE DATABASE m N w a a a e yeDtbs

B. Deleting Databases:

DROP DATABASE d t b s _ a e [, d t b s _ a e aaaenm a a a e n m ...]

C. Renaming a database

USE m s e atr GO EXEC s _ b p i n m O d a a ' i g e U e ' T u pdoto ylDt, Snl sr, re EXEC s _ e a e b ' y l D t ' ' y e D t ' prnmd mOdaa, mNwaa EXEC s _ b p i n m N w a a ' i g e U e ' F l e pdoto yeDt, Snl sr, as GO

D. Working With Tables


Traditionally known as CRUD - Create, Read, Update, and Delete a. Creating a Table i. syntax:

CREATE TABLE t b e a e (c l m _ a e c l m _ y e [(c l m _ i t [,c l m _ r c s o ])] alnm ounnm ountp ounwdh ounpeiin

example: CREATE TABLE p a t c rcie ( fae nm VARCHAR(20) NOT NULL, lae nm VARCHAR(30) NOT NULL, h r _ a e SMALLDATETIME NULL, iedt sn s CHAR(11) NOT NULL ) GO -- 'NOT NULL' is the default.

EXECUTE s _ e p p a t c -- shows structure of table phl rcie ii. ALTER TABLE practice ALTER TABLE X Z ADD m CHAR(1) NULL Y i GO

b. "SELECT INTO" Tables can also be created with the "SELECT INTO" construct SELECT select_list INTO new_table_name FROM table_list WHERE search_condition Note: if new_table_name starts with #, it will be put in the temp tables ##, it will be in temp tables and be global (accessable to all other sessions) Example using Temp tables:

www.fincher.org/tips/General/SQL.shtml

1/38

9/3/12

SQL Examples
SELECT * INTO #tempcustomers2 FROM customers SELECT * FROM #tempcustomers2

Temp tables go away when the server is restarted or at the end of the connection. c. Deleting a table: DROP TABLE table_name d. Add a column: ALTER TABLE SDSurveys ADD KQLogic VARCHAR (1000) NULL e. Add a column with check for existence first IF NOT EXISTS (SELECT * FROM I F R A I N S H M .COLUMNS NOMTO_CEA WHERE T B E N M = ' y a l N m ' AND C L M _ A E = ' e c l m ' AL_AE MTbeae OUNNM nwoun) BEGIN ALTER TABLE M T b e a e ADD n w o u n varchar(32) NOT NULL DEFAULT ' yalNm eclm ' END f. How to delete, or drop, a column: Always a good idea to test if the column is there if you are running from a script IF EXISTS (SELECT * FROM d o y c l m s b .s s o u n WHERE i = o j c _ d ' d o . P o e t ] ) d b e t i (N [ b ] [ r j c s ' AND n m = ' r j c M n g r ) ae Poetaae' ALTER TABLE P o e t DROP COLUMN [P o e t a a e ] rjcs rjcMngr g. Show list of columns in a table sp_columns table_name

E. Working With Rows


a. Inserting Rows into a Table i. Syntax: INSERT INTO t b e n m [(c l m _ d ,c l m _ d ...)] al_ae ouni1 ouni2 VALUES (v l e ,v l e ,...) au1 au2 eape: xmls INSERT INTO a t s (1996,' o d ) -- INTO is an optional k eyword in SQLServer uo fr' INSERT t b e a e VALUES (' ' b ,DEFAULT,i -- DEFAULT is a k ey word alnm a ,' ' ) INSERT INTO t t e VALUES(1001,' h O y s y ,' o e ' il T e d s e ' H m r ,NULL) ii. add multiple rows to a table INSERT INTO table (c 7 4 8 3 SELECT a ,c FROM ... 1 ,c ,c ,c ) ,b ,d

iii. add multiple rows to a table with stored procedure INSERT INTO table (c 7 4 8 3 1 ,c ,c ,c ) EXECUTE s _ y t r d p o e u e pmsoe_rcdr iv. INSERT rows from this database into a table in another database INSERT INTO O h r a a a e a e s r t e D t b s N m ..u e s SELECT * FROM u e s WHERE l g n d =' f n h r sr oii mice' b. UPDATEing Rows in a Table i. UPDATE changes the values in an existing row UPDATE t l SET c l = v l e o |e p b o a u |c l x r UPDATE t b e n m SET c l m _ d = e p WHERE c n i i n al_ae ouni xr odto

ii. Examples: update u e s set p s w r = ' e p s ' WHERE u e = ' u s ' sr asod nwas sr qet update u e s set p s w r = ' e p s ' WHERE (U e I > 1) AND (U e I < 113) sr asod nwas srD srD update u e s set p s w r = ' e p s ' change=' ' WHERE u e = ' u s ' sr asod nwas, Y sr qet

www.fincher.org/tips/General/SQL.shtml

2/38

9/3/12

SQL Examples
UPDATE d s o n s SET d s o n = d s o n + .1 WHERE l w t >= 100 icut icut icut oqy UPDATE e p o e s SET L A E = UPPER(L A E mlye NM NM)

iii. updating a value based on other tables UPDATE t t e SET y d s l s = ils t_ae (SELECT S M t ) U (q y FROM s l s ae WHERE s l s i l _ d = t t e .t t e i a e .t t e i ils il_d AND o d d t BETWEEN ' 1 0 / 4 AND ' 2 3 / 4 ) r_ae 0/19' 1/19'

iv. example of adding a record based on data in another table INSERT a u t SELECT dl j .m m e _ o a .s r e , a .c t , a .s a e u ebrn, d tet d iy d tt, a .p o e n , d hn_o D T A D Y 1, G T A E A E D (Y , E D T ()) FROM j v n l j -- aliasing juvenile to ju ueie u JOIN auta dl d -- aliasing adult to ju ON j .a u t m m e _ o = a .m m e _ o u dl_ebrn d ebrn WHERE (D T A D Y 18, j .b r h d t ) < G T A E A E D (Y , u it_ae E D T ())

a .z p d i,

c. Deleting rows from a Table DELETE FROM table_name [WHERE search_condition] example: DELETE FROM m t b e WHERE u e i < 50 yal srd DELETE t b e a e -- deletes all rows in a table (see "DROP TABLE" to delete a table) alnm TRUNCATE TABLE t b e a e -- deletes all rows, but doesn't log transaction alnm DELETE t t e WHERE t t e i in (SELECT t t e i FROM ...) ils il_d il_d d. How to format a number with two decimal places -- this will return a field 13 characters wide, 10 before the decimal point and two after select CONVERT(DECIMAL(12,2),m F e d from m T b e yil) yal -- if your number is larger than that you get this error: -- Msg 8115, Level 16, State 8, Line 1 -- Arithmetic overflow error converting int to data type numeric. -- or you can use the STR function select s r y i l , 12, 2) from m T b e t (m F e d yal e. Example of CAST, Datepart, and STR In the example below, "dtime" is a column containing the datetime. "datepart(yy,dtime)" produces the year, "str(datepart(dy,dtime),3)" produces a right justified day-of-the-year. SELECT c s (d t p r (y ,d i e as varchar(4)) + ' ' + s r a e a t y t m ),3) as ' e r D y at aeat y tm) t (d t p r (d ,d i e Ya a' CUT O N (time) AS ' e Q e t o P g s , Ky usin ae' ag v (time) AS ' v t m ( s c ' ag ie me) FROM s r s o d n p g t m s depnetaeie WHERE n m =' e ' ae Ky group by c s (d t p r (y ,d i e as varchar(4)) + ' ' + s r a e a t y t m ),3) at aeat y tm) t (d t p r (d ,d i e order by c s (d t p r (y ,d i e as varchar(4)) + ' ' + s r a e a t y t m ),3) asc at aeat y tm) t (d t p r (d ,d i e

The results: Year D y Key Q e t o P g s a g time (m e ) a usin ae v sc --------- ------------------ --------------2004 51 13 768 2004 54 10 747 2004 56 6 1090 2004 57 34 702 ... 2004 351 1 6000 2004 362 14 548

www.fincher.org/tips/General/SQL.shtml

3/38

9/3/12
2005 2005 2005 2005 2005 4 5 7 10 11

SQL Examples
3 20 10 1 1228 629 834 469 3593 269

F. SQL Server Utilities


a. osql - the command line batch interface to SQL Server i. To EXECUTE a single statement use the -Q option o q -U o -P m p s w r " sl mi "yasod -Q I S R D T _ A L ( o u n , c l m 2 v l e c l _ a u , c l _ a u " "NET AATBE clm1 oun) aus o1vle o2vle

i. To have osql run a script file, (e.g., testSQL.SQL), use the -i option o q -U y s r d -P m p s w r " -i e t Q .S L sl muei "yasod tsSL Q ii. Then to get things back out use the -o option: o q -U o -P sl mi -Q S L C c l m 1 c l m 2 F O D T _ A L " -o u p t f l "EET oun, oun RM AATBE Otu_ie iii. To specify a host: -H delphi iv. To specify a server: -S delphi v. To specify a server running SQLExpress: -S "delphi\SqlExpress" vi. to specify a database: -d db3 vii. to surpress the headers: -h-1 viii. to specify a separator: -s! ix. to set the line width to 5000: -w5000 A better way to handle the password is to set an environmental variable, "OSQLPASSWORD", so the "-U" option may be omitted. b. To get a list of all databases on a server SELECT DISTINCT n m FROM S S A A A E ae YDTBSS c. To see which service pack (if any is installed) SELECT S R E P O E T (' r d c L v l ) EVRRPRY Poutee' Rtrs eun: 'T'= sipn vrin RM hpig eso. 'P'= sriepc vrin Sn evc ak eso 'n, = bt vrin B' ea eso. d. To impersonate a user: STSR'yenm' EUE mnwae GO (S L s a e e t ) Q ttmns

use SETUSER to get back to the original user e. To add a login for a new user for a database: EXECUTE s _ d u e ' e l g n d padsr nwoii' EXECUTE s _ d l g n ' e l g n d ,' a s o d padoi nwoii' pswr'

f. To find the size of all databases EXEC s _ e p b phld -- or for one database

www.fincher.org/tips/General/SQL.shtml

4/38

9/3/12

SQL Examples
EXEC s _ e p b ' b a e phld dnm' g. To get a list of all databases on a server SELECT n m FROM m s e ..s s a a a e ae atr ydtbss -- or EXEC s _ a a a e pdtbss h. To grant a user permission to a database: USE m d t b s yaaae EXECUTE s _ d u e n w o i i padsr elgnd i. To grant a user permission to a database table: GRANT [EXECUTE|ALL] ON T b e a e TO m l g n d alNm yoii j. Note: If a stored procedure is not the first item in a series of SQL statements, it must be prefaced with 'EXECUTE'. k. To unload a dll: dbcc xp_netq (FREE) l. To have SQLServer run a simple diagnostic on a db named mydb: dc cekb yb b c h c d (m d ) also try dbcc checkalloc(db4) m. To get the name of the current database SELECT d _ a e b n m () n. to show the names of all databases USE m s e atr SELECT n m FROM s s a a a e ae ydtbss o. to get the date SELECT g t a e e D t ()

G. SQL Server Results


a. Three ways to change column headings SELECT F r t = a _ n m , is ufae a_nm 'atNm' ulae Ls ae, a _ d AS ' d n i i a i n N m e ' ui Ietfcto ubr FROM a t o s uhr Poue: rdcs Frt is Ls Nm at ae Ietfcto Nme dniiain ubr ----------------------------------------------------------Jhsn ono Wie ht 172-32-1176 Mroi ajre Gen re 213-46-8915

b. Retrieving Results i. General to get unique values: SELECT DISTINCT c l m _ a e FROM m t b e -- note: this also does an implicit sort ounnm yal ii. to get frequency of column values: SELECT c l m _ a e C U T o u n n m ) as m c u t FROM t b e n m o u n n m , O N (c l m _ a e yon al_ae GROUP BY c l m _ a e ORDER BY m c u t [ASC | DESC] ounnm yon

www.fincher.org/tips/General/SQL.shtml

5/38

9/3/12

SQL Examples
iii. to join two tables the SQLServer way: SELECT t b e .A , t b e .B FROM t b e , t b e ala 1 alb 1 ala alb WHERE t b e .m k y = t b e .m k y ala ye alb ye

iv. to get info from two tables UPDATE t b e SET m c l m = ' ' WHERE u e i IN al1 youn 2 srd ( SELECT u e i FROM t b e WHERE t b e .d s a <> ' o e a u ' srd al2 al2 ist smvle)

c. Aliasing tables SELECT a i l _ d a u i , b u i .t t e i , .a _ d .a _ d FROM t t e u h r a ilato INNER JOIN t t e u h r b ilato ON a i l _ d = b i l _ d .t t e i .t t e i WHERE a u i < b u i .a _ d .a _ d d. how to preface info in a column with a string, 'x-', UPDATE m t b e SET m c l m = ' - +m c l m yal youn x' youn e. wildcards: Wildcard % _ [] ([abcdef]) [^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]) Meaning Any string of zero or more characters Any single character Any single character within the specified range ([a-f]) or set

LIKE ' c ' s a c e for all n m s t a begin with t e l t e s " c (M B d e ). M% erhs ae ht h etr M" cadn SELECT c l m _ a e FROM table WHERE m s r n LIKE ' [ Y ] ounnm ytig %XZ' To f n all fields w i h c n a n a c r i g return: id hc oti arae SELECT u e i , Z p FROM m t b e WHERE Z p like ' ' srd i yal i % +char(10)+' ' % f. Advanced Topics in Retrieving Results i. Limit the number of rows returned (note this can be very dangerous since it affects all subsequent commands) SET r w o n 4 ocut SELECT T b e a e o u n a e a l N m ,C l m N m ,Language T t e U T b e e c i t o ,L g c i l ,L _ a l ,D s r p i n o i ,Type FROM D t G o p aaru SET r w o n 0 -- turns off rowcounting ocut

ii. UNION This concatenates result set together USE s l e o qdm SELECT * FROM a t o s --23 rows uhr UIN NO SELECT * FROM n w u h r --8 rows eatos ORDER BY a t o s u l a e u h r .a _ n m UNION will surpress duplicates, use UNION ALL to show all rows iii. GROUP BY and HAVING /* ** This query will search through the member_no column look ing for ** member numbers that have duplicate values and also show the number ** of duplicates found for each member number. */ SELECT m m e _ o N m e _ f D p = c u t ebrn, ubro_us o n (*) FROM m m e ebr GROUP BY m m e _ o ebrn

www.fincher.org/tips/General/SQL.shtml

6/38

9/3/12

SQL Examples
HAVING c u t > 1 o n (*)

H. Stored Procedures
a. Stored Procedures i. General syntax of stored procedure

CREATE P O E U E p a e RCDR nm @a vrye ealvle vr vrye v r a t p [=d f u t a u ][,@ a 2 a t p ] AS ... GO ii. Declaring Variables

DECLARE @ a n m type[,@ a n m type]* -- to define a variable vrae vrae DECLARE @ int x SELECT @ = 5 x

iii. Simple Example

CREATE P O E U E e p i t RCDR mls AS SELECT e p a e t t e s l r mnm, il, aay FROM e p m ORDER BY t t e il GO

iv. Simple Example with one argument

CREATE P O E U E A t o S a e RCDR uhrtt @ t t v r CHAR(2) = ' _ -- if no arg passed, '__' is the default saea _' AS SELECT s a e a _ n m , a _ n m FROM a t o s WHERE s a e LIKE tt, ufae ulae uhr tt @ t t v r ORDER BY a _ n m GO To t s i : EXECUTE A t o S a e saea ulae et t uhrtt 'T U'

v. Fun things to know and tell about Stored Procedures 1. Stored Procedures can have up to 255 parameters 2. EXECUTE sp_helptext mystoredproc -- shows the source code 3. EXECUTE sp_depends mystoredproc -- see what tables are associated with the sp 4. SELECT name FROM sysobjects WHERE type = 'P'-- to see all the stored procedures 5. sp_makestartup -- makes an existing sp a startup procedure 6. sp_ummakestartup -- removes an existing sp a startup procedure 7. in transact sql to get the results of a select into a variable: SELECT @ a g a e t i g D = M X a g a e t i g D FROM LnugSrnI A (L n u g S r n I ) LnugSrn agaetig vi. drop an existing sp

IF EXISTS ( SELECT n m FROM s s b e t WHERE type = ' ' AND n m = ' d a u t ) ae yojcs P ae addl' DROP P O E U E a d d l RCDR daut

or you can do this:

www.fincher.org/tips/General/SQL.shtml

7/38

9/3/12

SQL Examples
IF O J C P O E T (o j c _ d d o Y u S o e P o N m ' N I P o e u e ) = 1 B E T R P R Y b e t i (' b . o r t r d r c a e ), ' s r c d r ' DROP P O E U E [d o o r t r d r c a e RCDR b ].[Y u S o e P o N m ] GO

vii. example of complete sp:

CREATE P O E U E a d d l RCDR daut @atae lsnm sottig hrsrn, @isnm frtae sottig hrsrn, @identa mdliiil l t e = NULL, etr @tet sre s o t t i g = NULL, hrsrn @iy ct s o t t i g = NULL, hrsrn @tt sae s a e o e = NULL, ttcd @i zp z p o e = NULL, icd @hn_o poen p o e u b r = NULL hnnme AS DECLARE @ e b r n m m e _ o mme_o ebrn IF @ i d e n t a = NULL OR mdliiil @tet sre = NULL OR @iy ct = NULL OR @tt sae = NULL OR @i zp = NULL OR @hn_o poen = NULL BEGIN PRINT " " PRINT " P e s r e t r t i A u t M m e . lae ene hs dl ebr" PRINT " Y u m s p o i e L s n m , F r t n m , M d l i i i l " o ut rvd at ae is ae ide nta, PRINT " Sre,Ct,Sae Zp adPoenme. tet iy tt, i, n hn ubr" PRINT " " RETURN END BEGIN TRANSACTION SELECT @ e b r n = (SELECT m x e b r n ) FROM m m e H L L C ) + 1 mme_o a (m m e _ o ebr ODOK INSERT m m e ebr ( mme_o lsnm, frtae mdliiil poorp) ebrn, atae isnm, identa, htgah VALUES (@ e b r n , @ a t a e @ i s n m , @ i d e n t a , NULL ) mme_o lsnm, frtae mdliiil IF @ e r r <> 0 @ro BEGIN ROLLBACK TRAN RETURN END INSERT a u t dl ( mme_o sre, ct, sae zp poen, ep_ae ebrn, tet iy tt, i, hn_o xrdt) VALUES (@ e b r n , @ t e t @ i y @ t t , @ i , @ h n _ o d t a d m m e _ o s r e , c t , s a e z p p o e n , a e d (year,1,g t a e edt IF @ e r r != 0 @ro BEGIN ROLLBACK TRAN RETURN END PRINT " PRINT " PRINT " " **AutMme add** * dl ebr de * " "

C M I TRANSACTION OMT GO

viii. Another Example

CREATE P O E U E o e d e b o s RCDR vru_ok AS SELECT m m e .l s n m ,c p _ o u _ a e FROM l a e b r a t a e o y n ,d e d t on JOIN m m e ON l a .m m e _ o = m m e .m m e _ o ebr on ebrn ebr ebrn WHERE D T D F (D Y E D T (),d e d t )>1 A E I F A ,G T A E u _ a e GO

www.fincher.org/tips/General/SQL.shtml

8/38

9/3/12

SQL Examples

ix. OUTPUT parameter Example using the OUTPUT parameter ** T i s r p f l c e t s a p o e u e L A C U T hs cit ie rae rcdr, ONON, ** t a r t r s a status o 0 if a m m e h s a y ht eun f ebr a n ** l a s If a m m e h s n l a s i r t r s a on. ebr a o on, t eun ** status o -1. f USE l b a y irr GO CREATE P O l a c u t @ e b r n m m e _ o @ o n o n int O T U AS IF EXISTS (SELECT RC onon mme_o ebrn, lacut UPT * FROM l a WHERE m m e _ o = @ e b r n ) on ebrn mme_o BEGIN SELECT @ o n o n =C U T FROM l a WHERE m m e _ o = @ e b r n RETURN l a c u t O N (*) on ebrn mme_o (0) END ELSE RETURN (-1) GO --NOTE: if any syntax errors in a batch, nothing in batch runs -- all the statements are rolled together for syntax check ing -- if any statements have problems the "GO" is not executed.

I. Control of Flow
a. Control of Flow i. IF

IF(c n i i n odto) BEGIN ... END ELSE BEGIN ... END

Eape xml:

IF (SELECT C U T e b r n ) O N (m m e _ o FROM l a on WHERE m m e _ o = @ a a ) <= 4 ebrn prm RETURN 1 ELSE RETURN 2 GO

ii. WHILE 1. Syntax

WIEcniinBGN..ED BEKCNIU HL odto EI . N RA/OTNE 2. Example of simple WHILE statement

set n c u t on oon declare @ int SELECT @ = 0 i i while (@ < 10) i BEGIN SELECT ' = ' + convert(char(5),@ ) i i SELECT @ = @ + 1 i i END set n c u t o f oon f

Code to insert 3000 rows into the database

www.fincher.org/tips/General/SQL.shtml

9/38

9/3/12

SQL Examples

DECLARE @ INT i SET @ =10000 i WHILE(@ <= 30000) i BEGIN INSERT INTO m t b e (date, t r a , l v l l g e , s r e , u e i , m s a e yal hed ee, ogr evr srd esg) VALUES (G T A E 0 0 ' I F ' X Z ' L g i e ,@ ,' y m s a e ) E D T (),' 0 0 ,' N O ,' Y 1 ,' o F l ' i m e s g ' SET @ =@ +1 i i END iii. Delete rows from a table in small batches like slicing a salami. Using the WHILE statement this stored procedure deletes records older than a specific number of days. Deleting all the rows can cause the database to freeze or the query can timeout. -- trims table to only k eep specific number of previous days in table which must have a datetime field named 'dtime' -- example: EXEC sd_trimTable 'practice', 50 -this would remove all rows older than 50 days in slices of 1000 IF O J C P O E T (o j c _ d d o s _ r m a l ' N I P o e u e ) = 1 B E T R P R Y b e t i (' b . d t i T b e ), ' s r c d r ' DROP P O E U E d o d t i T b e R C D R b .s _ r m a l GO CREATE P O E U E s _ r m a l @ a l N m char(128), @ r m a s int RCDR dtiTbe tbeae tiDy AS DECLARE @ r m a e datetime tiDt DECLARE @ m char(240) cd DECLARE @ o n e int cutr SET @ r m a e = D T A D a ,-@ r m a s E D T ()) tiDt A E D (d y t i D y ,G T A E SET @ o n e = 1 cutr SET @ m = ' E E E T P ( 0 0 F O ' (@ a l N m )+' W E E d i e < ' ' + CONVERT cd DLT O 10) RM + tbeae HR tm ' SELECT @ m cd WHILE 1 = 1 BEGIN EXEC (@ m ) cd IF @ R W O N = 0 @OCUT BEK RA W I F R D L Y ' 0 0 : 0 2 --give other processes time to access table ATO EA 0:00.' END GO

iv. Example to show space used by each table

DECLARE @ e t VARCHAR(30) nx SELECT @ e t = ' ' --Mak es it "not null" nx WHILE @ e t IS NOT NULL nx BEGIN SELECT @ e t = M N a e nx I (n m ) FROM s s b e t yojcs WHERE type = ' ' --User Tables U AND n m > @ e t ae nx ORDER BY n m ae EXECUTE s _ p c u e @ e t psaesd nx END

v. RETURN used for 1 non-null integer CREATE P O E U E c e k e RCDR hcmm @ a a INT prm AS IF (SELECT C U T e b r n ) O N (m m e _ o FROM l a on WHERE m m e _ o = @ a a ) <= 4 ebrn prm RETURN 1 ELSE RETURN 2 GO To use t i c n t u t hs osrc: DECLARE @ e INT rt EXECUTE @ e = c e k e 100 rt hcmm b. Misc commands

www.fincher.org/tips/General/SQL.shtml

10/38

9/3/12

SQL Examples
i. Example to create many databases set n c u t on oon declare @ int SELECT @ = 2 i i declare @ i char(1) s while (@ < 5) i BEGIN SELECT @ i = convert(char(1),@ ) s i SELECT ' = ' + convert(char(5),@ ) i i exec(' R A E D T B S d ' s +' O s d t = 1 L G O s l g = 1 ) C E T A A A E b +@ i N na O N no ' SELECT @ = @ + 1 i i END set n c u t o f oon f

ii. How to trim down the size of log files in MSSQL 2008 This is dangerous for production machines, but for development boxes where you really don't care about recovery this should reduce the log size. ALTER DATABASE [M D t b s N m ] SET R C V R S M L yaaaeae EOEY IPE go B C U l g [M D t b s N m ] WITH T U C T _ N Y AKP o yaaaeae RNAEOL go D C S R N D T B S ([M D t b s N m ], 10, T U C T O L ) BC HIKAAAE yaaaeae RNAENY go

iii. How to see all collations in a database SELECT T B E N M , C L M _ A E A A T P ,C L A I N N M FROM I F R A I N S H M .COLUMNS A L _ A E O U N N M ,D T _ Y E O L T O _ A E NOMTO_CEA WHERE C L A I N N M IS NOT null OLTO_AE

iv. How to write the SQL to change all collation sequences from Paul Deen, http://members.chello.nl/p.deen7/knowledgebase/sql_change_collation.htm SELECT ' l e T b e [ + t b e c t l g + ' . ' + t b e s h m + ' . ' + t b e n m Atr al ' al_aao ][ al_cea ][ al_ae FROM I F R A I N S H M .COLUMNS NOMTO_CEA WHERE c l a i n n m <> ' Q _ a i 1 G n r l C 1 C _ S olto_ae SLLtn_eea_P_IA' AND d t _ y e in (' h r , ' a c a ' ' e t ) aatp ca' vrhr, tx' AND t b e n m in (select t b e n m from I F R A I N S H M .tables where t b e t p = al_ae al_ae NOMTO_CEA al_ye

v. How To Obtain The Size Of All Tables In A SQL Server Database From http://therightstuff.de/CommentView,guid,df930155-f60f-4f56-ab33f1352ff091a1.aspx SET N C U T ON OON DC UDTUAE B C P A E S G (0) -- DB size. EXEC s _ p c u e psaesd -- Table row counts and sizes. CREATE TABLE #t ( [n m ] N A C A (128), ae VRHR [r w ] CHAR(11), os r s r e VARCHAR(18), eevd data VARCHAR(18), i d x s z VARCHAR(18), ne_ie u u e VARCHAR(18) nsd ) INSERT #t EXEC sp_msForEachTable 'EXEC sp_spaceused ''?''' SELECT * FROM #t -- # of rows. SELECT S M A T o s AS int)) AS [r w ] U (C S ([r w ] os FROM #t DROP TABLE #t vi. Print the current time immediately in seconds we use RAISERROR since it's supposably not buffered

www.fincher.org/tips/General/SQL.shtml

11/38

9/3/12

SQL Examples
DECLARE @ t char(240) sr SELECT @ t = convert(varchar(19), g t a e 121) sr e d t (), RAISERROR(' r m i g 1 0 0 0 r w a % ' 0, 1, @ t ) WITH N W I Timn 0,0 os t s, sr OAT vii. sp_tables s _ a l s -- to show a list of tables in a database: ptbe -- or SELECT n m FROM s s b e t WHERE type = ' ' -- to see the user tables only ae yojcs u c. Change the size of varchar column You may need to add the 'NOT NULL' option if your column is an indexed column ALTER TABLE M T b e a e ALTER COLUMN M C l m N m varchar(32) yalNm younae d. Show all constraints of type DEFAULT_CONSTRAINT SELECT * FROM s s b e t y .o j c s WHERE t p _ e c LIKE ' C N T A N ' yeds %OSRIT AND t p _ e c = ' E A L _ O S R I T yeds DFUTCNTAN' e. Read more than 256 characters from an ntext field OK, there's the right way to do this with pointer and READTEXT, but you can cheat and use the SUBSTRING command to read from an ntext field SELECT T P 1000 O SUBSTRING([T x D t ],1,255) etaa ,SUBSTRING([T x D t ],256,400) etaa ,[D r t o ]/1000 as d r t o M uain uains FROM [z z z b ].[S W i t r _ 1 3 z z ].[d o D h s o y 1 0 ] where c u is not NULL and t x d t is not null and c u > 0 p etaa p order by d r t o desc uain f. Modifying column properties with constraints Sometimes you can't modify a column if it has a constraint. First you must drop the constraint, then modify the column, then re-add the constraint. IF EXISTS (SELECT * FROM s s n e e WHERE o j c _ d = O J C _ D ' d o . S m l S u c s ' y .i d x s beti B E T I (N [ b ] [ a p e o r e ] ALTER TABLE [d o a p e o r e ] DROP C N T A N [P _ a p e o r e ] b ].[S m l S u c s OSRIT KSmlSucs alter table S m l S u c s Alter Column n m varchar(65) NOT NULL apeore ae /****** Object: Index [PK_SampleSources] Script Date: 08/06/2010 09:11:22 ******/ ALTER TABLE [d o a p e o r e ] ADD C N T A N [P _ a p e o r e ] PRIMARY KEY C U T R D b ].[S m l S u c s OSRIT KSmlSucs LSEE ( [n m ] ASC ae )WITH (P D I D X = O F S A I T C _ O E O P T = O F S R _ N T M D = O F I N R _ U _ E A_NE F, TTSISNRCMUE F, OTI_EPB F, GOEDPKY

g. Working with parameterized SQL You have to declare and set the variable declare @ d int i select @ d = 4140 i SELECT u e i FROM m t b e WHERE u e i > @ d ORDER BY u e i srd yal srd i srd h. loop thru all the tables in a database and UPDATE their Statistics set n c u t on oon declare @ e t varchar(30) nx SELECT @ e t = ' ' nx while @ e t IS NOT NULL nx BEGIN SELECT @ e t = M N a e FROM s s b e t WHERE type = ' ' and n m > @ e t nx I (n m ) yojcs u ae nx SELECT ' e t i ' + @ e t nx s nx IF @ e t IS NOT null nx BEGIN EXECUTE (' P A E S A I T C ' + @ e t UDT TTSIS nx) END END

www.fincher.org/tips/General/SQL.shtml

12/38

9/3/12

SQL Examples
set n c u t on oon

i. Loop through all the tables in a database and print the number of rows set n c u t on oon declare @ a l n m varchar(90) tbeae declare @ y o n varchar(90) mcut SELECT @ y o n = ' ' mcut SELECT @ a l n m = ' ' tbeae while @ a l n m IS NOT NULL tbeae BEGIN SELECT @ a l n m = M N a e FROM s s b e t WHERE type = ' ' and n m > @ a l n m tbeae I (n m ) yojcs u ae tbeae IF @ a l n m IS NOT null tbeae BEGIN SELECT @ y o n = ' e e t ' ' t b e a e ' , c u t * f o ' + @ a l n m mcut s l c ' +@ a l n m +' ' o n ( ) r m tbeae execute (@ y o n ) mcut END END

j. loop thru all the databases and print the name. (Useful for performing operations on each database). set n c u t on oon use m s e atr declare @ e t varchar(30) nx SELECT @ e t = ' ' nx while @ e t IS NOT NULL nx BEGIN SELECT @ e t = M N a e FROM s s a a a e WHERE d i > 5 AND n m > @ e t nx I (n m ) ydtbss bd ae nx --SELECT 'next is ' + @next IF @ e t IS NOT null nx BEGIN SELECT ' o k n a d t b s ' n x L o i g t a a a e ,@ e t END END set n c u t on oon k. RAISERROR This writes a message to the console and event log RAISERROR(' * t i i m m s a e ,16,1) WITH L G * hs s y esg' O RAISERROR(' * t i i m m s a e ,s r i y t t ) WITH L G * h s s y e s g ' e v t ,s a e O --error serverity 1-16 ok , 17-18 serious, 19-25 fatal l. Adding Space to a Database: Add 1 MEG: ALTER DATABASE l b a y ON l b a y d v = 1 -- MEG to increase by irr irr_e1 To increase size of log file: ALTER DATABASE l b a y ON l g e n m = s z in 2 irr odvae ie k m. To make the log file less verbose ALTER DATABASE M D t b s SET R C V R S M L yaaae EOEY IPE n. PRINT PRINT ' h s i a p i t ti s rn' PRINT ' E E T s r a d e t e s m t i g b t n t q i e s m t m s y u n e a P I T SLC ot os h ae hn, u o ut, oeie o ed RN'

The PRINT statement is buffered. To get your output immediately (unfortunately there's

www.fincher.org/tips/General/SQL.shtml

13/38

9/3/12

SQL Examples
no FLUSH command) you can use RAISERROR instead. set @ s = convert(char(25),G T A E + ' m c o m s a e mg E D T ()) : y ol esg' RAISERROR ( @ s ,0,1) WITH N W I mg OAT o. CASE statement -- SIMPLE CASE EXPRESSION SELECT C t g r = aeoy CASE type WHEN ' o u a _ o p T E ' o u a C m u i g pplrcm' HN Pplr optn' WHEN ' o _ o k mdco' TE 'oenCoig HN Mdr okn' WHEN ' u i e s bsns' TE 'uies HN Bsns' WHEN ' s c o o y pyhlg' TE 'scooy HN Pyhlg' WHEN ' r d c o ' ta_ok TE 'rdtoa Coig HN Taiinl okn' ELSE ' o Y t C t g r z d Nt e aeoie' END, CONVERT(varchar(30), t t e AS ' h r e e T t e , il) Sotnd il' Pie rc FROM t t e ils WHERE p i e IS NOT NULL rc ORDER BY type COMPUTE A G r c ) BY type V (p i e p. SEARCHED CASE EXPRESSION SELECT m e b r n , .m m e _ o m atae .l s n m , 'ebrTp'= Mme ye CASE WHEN m e b r n IN .m m e _ o (SELECT m m e _ o ebrn FROM j v n l j ueie WHERE j e b r n = m e b r n ) .m m e _ o .m m e _ o TE 'ueie HN Jvnl' ELSE ' d l ' Aut END, ep_ae xrdt FROM m m e m a u t a j v n l j ebr , dl , ueie WHERE j d l _ e b r n = a e b r n .a u t m m e _ o .m m e _ o AND (m e b r n = a e b r n OR m e b r n = j e b r n ) .m m e _ o .m m e _ o .m m e _ o .m m e _ o AND e p _ a e < G T A E xrdt E D T () ORDER BY m e b r n .m m e _ o

2. BuiltIn Functions
A. BuiltIn Functions
a. Aggregate Functions: SUM, AVG, MIN, MAX, and COUNT example: SELECT S M t _ a e ) FROM t t e U (y d s l s ils to g t t e n m e o s m t i g e h ubr f oehn: SELECT C U T FROM D t g o p WHERE Language = ' N ' O N (*) aaru EU CUT O N ([ALL|DISTINCT]e p e s o ) -- note: count can have options xrsin - GROUP BY - COMPUTE or COMPUTE BY - WITH C B or WITH R L U UE OLP

b. Example of COMPUTE SELECT r s o d n s u v y a e e p n e t .s r e N m , m n i V l e as ' e i e m n a e , i (m n a u ) dsrd i g' m n 1 as ' c u l m n a e , i (a ) ata i g' a s i (m n a u ) - m n 1 as ' i f m n a e , b (m n i V l e i (a )) df i g' m x a V l e as ' e i e m x a e , a (m x a u ) dsrd a g' m x 1 as ' c u l m x a e , a (a ) ata a g' a s a (m x a u ) - m x 1 as ' i f m x a e , b (m x a V l e a (a )) df a g' (m n i V l e a (m x a u ))/2 as ' e i e a g a e , i (m n a u )+m x a V l e dsrd v g' a g 1 as ' c u l a g a e , v (a ) ata v g' a s i (m n a u )+m x a V l e b ((m n i V l e a (m x a u ))/2 - a g 1 as ' i f a g a e , v (a )) df v g'

www.fincher.org/tips/General/SQL.shtml

14/38

9/3/12

SQL Examples
a s i (m n a u ) - m n 1 b (m x a V l e - m x 1 a s i (m n a u ) + b (m n i V l e i (a ))+a s a (m x a u ) a (a ))+ b ((m n i V l e mx aVle a (m x a u ))/2 - a g 1 as ' o a S e ' v (a )) Ttl kw from r s o d n s join s r e D r c o Q o a on s r e D r c o Q o a .s r e N m = epnet uvyietruts uvyietruts uvyae rsodns uvyae e p n e t .s r e N m --where respondents.surveyName = 'EClientE2' and q o a u s i n = ' a e utQeto _g' group by r s o d n s u v y a e e p n e t .s r e N m COMPUTE c u t e p n e t .s r e N m ), o n (r s o d n s u v y a e s m b (m n i V l e - m n 1 b (m x a V l e - m x 1 u (a s i (m n a u ) i (a ))+a s a (m x a u ) a (a ))+ a s i (m n a u )+m x a V l e b ((m n i V l e a (m x a u ))/2 - a g 1 v (a )))

c. NULLIF (expr1,epr2) returns null if the two expressions are equal SELECT A G U L F o a t p r 100)) V (N L I (r y l y e , AS ' v r g S a e R y l y % Aeae hrd oat ' FROM t t e u h r ilato d. COLESCE(expr1,expr2,...exprN) -- returns first non-null value e. ISNULL Wonderful function that returns a specified value (in this example -1) if the query returns null. SELECT I N L ( (SELECT u e i FROM b l i g WHERE p d = @ i ) ,-1) SUL srd iln i pd f. Misc /* What database is now open? */ SELECT " p n D t b s i : ,D _ A E O e a a a e s " B N M ()

/* What is it's unique database identifier? */ SELECT " a a a e I i : ,D _ D D t b s D s " B I ()

/* What is the current host machine name? */ SELECT " o t N m i : ,H S _ A E H s a e s " O T N M ()

/* What is the login name of the current user? */ SELECT " o i N m i : , S S R N M () Lgn ae s" UE_AE

/* What is the database user name of the current user? */ SELECT " B U e N m i : ,U E _ A E D s r a e s " S R N M () g. ARITHMETIC OPERATORS SELECT p i e rc, (p i e * 1.1) AS ' e P i e , rc Nw rc' tte il FROM t t e ils --Round to 2 decimals SELECT p i e rc, CONVERT(M N Y (p i e * 1.1)) AS ' e P i e , OE, rc Nw rc' tte il FROM t t e ils h. MATHEMATICAL FUNCTIONS A S (n m r c e p ) A s l t v l e o t e n m r c B uei_xr boue au f h uei C I I G (n m r c e p ) S a l s i t g r g e t r t a or e u l to ELN uei_xr mlet nee rae hn qa tenmrcepeso. h uei xrsin C S (f o t e p ) T i o o e r c c s n o t e s e i i d a g e (in r d a s O la_xr rgnmti oie f h pcfe nl ain) R N ([s e ]) R n o a p o i a e n m r c (float) v l e between 0 and 1, AD ed adm prxmt uei au R U D (n m r c e p , l n t ) N m r c e p e s o r u d d o f to t e ON uei_xr egh uei xrsin one f h l n t (or p e i i n egh rcso)

www.fincher.org/tips/General/SQL.shtml

15/38

9/3/12
Example:

SQL Examples

SELECT p i e rc, F O R r c ) AS ' l o P i e , L O (p i e For rc' C I I G r c ) AS ' e l n P i e E L N (p i e Ciig rc' FROM t t e ils

3. TRANSACTIONS
BEGIN TRANSACTION -- forces all or none of the following commands INSERT ... INSERT ... IF() ROLLBACK TRANSACTION C M I TRANSACTION OMT

4. Using @@error
IF @ e r r <> 0 BEGIN ROLLBACK TRAN @ro RETURN END

5. LOCKS
SELECT * FROM a t o s (n l c ) uhr ook -- will read even lock ed pages

SET TRANSACTion i o a i n l v l READ U C M I T D -- lets reader look slto ee NOMTE SELECT * FROM a t o s uhr s _ a l o t o t b e a e I S R r w l c ' t u -- to turn on InsertRowLock p t b e p i n a l n m ,' N E T o o k , r e

6. String Functions
A. Misc
CONVERT (type, v r a) C n e t t p s (e , convert(r a ,' 2 5 )) ovrs ye g el 1.' RTRIM (c a _ x r R m v s trailing b a k . hrep) eoe lns LOWER (c a _ x r C n e t u p r a e c a a t r data to l w r a e hrep) ovrs pecs hrce oecs. LTRIM (c a _ x r R m v s leading b a k . hrep) eoe lns SUBSTRING(e p e s o , s a t l n t ) R t r s p r o a xrsin tr, egh eun at f c a a t r or binary s r n . hrce tig S U F (c a _ x r , s a t l n t , c a _ x r ) D l t s l n t TF hrep1 tr, egh hrep2 eee egh c a a t r FROM c a _ x r a s a t and t e i s r s hrces hrep1 t tr hn net c a _ x r into c a _ x r a s a t hrep2 hrep1 t tr. UPPER (c a _ x r C n e t l w r a e c a a t r data to u p r a e hrep) ovrs oecs hrce pecs.

Eape: xmls

SELECT ' h p i e f r ' + Te rc o CONVERT(char(38), t t e -- doing a substring but appends spaces to mak e it 38 il) + ' i $ + CONVERT(varchar(10), p i e FROM t t e s ' rc) ils SELECT f a e + ' ' + l a e + ' w s h r d o ' + nm nm a ie n CONVERT(char(8), h r _ a e 1) iedt, FROM e p o e mlye SELECT LOWER(l s n m + SUBSTRING(f r t a e atae i s n m ,1,2)) FROM m m e WHERE l s n m = ' N E S N ebr atae ADRO' --Round to 2 decimals SELECT p i e rc, CONVERT(M N Y (p i e * 1.1)) AS ' e P i e , OE, rc Nw rc' tte il FROM t t e ils -- shows last name, authors first initial SELECT a _ n m + ' ' + SUBSTRING(a _ n m ,1,1) + ' ' AS ' a e , ulae , ufae . Nm' a_d ui

www.fincher.org/tips/General/SQL.shtml

16/38

9/3/12
FROM a t o s uhr

SQL Examples

B. Dates
/* What is the current date and time? */ SELECT ' u r n d t a d t m i ' E D T () C r e t a e n i e s ,G T A E /* What is a week from today? */ SELECT ' w e f o t d y i ' A E D (W E ,1,G T A E A e k r m o a s ,D T A D E K E D T ()) /* How many days between now and end of century? */ SELECT ' a s u t l Y a 2 0 i ' A E I F A ,G T A E 0 / 1 2 0 ' D y n i e r 0 0 s ,D T D F (D Y E D T (),' 1 0 / 0 0 ) /* What is the name of the current month? */ SELECT ' a e o t i m n h i ' A E A E O T ,G T A E N m f h s o t s ,D T N M (M N H E D T ()) /* What is the name of the day for today? */ SELECT ' a o t e w e i ' A E A E E K A ,G T A E D y f h e k s ,D T N M (W E D Y E D T ()) /* What is the day of the month? */ SELECT ' u r n d y o m n h i ' A E A T A , G T A E C r e t a f o t s ,D T P R (D Y E D T ()) /* get date differences in seconds */ SELECT u e I , D T D F (s c n , d i e , g t a e FROM r s o d n s srD AEIF eod tm e d t ()) epnet

How to sum counts over a day into a total. Sometimes you have a field you want to find the total for a day, like how many invoices did we send each day of this last year. Here's and example of getting a count for every day of the year SELECT d t p r (year,d i e AS ' e r ,d t p r (m n h t m ) AS ' o t ' a e a t a ,d i e AS aeat tm) y a ' a e a t o t ,d i e m n h ,d t p r (d y t m ) GROUP BY d t p r (year,d i e a e a t o t ,d i e a e a t a ,d i e aeat t m ),d t p r (m n h t m ),d t p r (d y t m ) ORDER BY d t p r (year,d i e a e a t o t ,d i e a e a t a ,d i e aeat t m ),d t p r (m n h t m ),d t p r (d y t m )

C. How to import a CSV file into a SQL table?


B L INSERT M T b e a e FROM ' : M C v i e t t UK yalNm c\ysFl.x' WITH ( FEDEMNTR= '' ILTRIAO ,, RWEMNTR= 'n OTRIAO \' ) GO

7. ORDER BY
ORDER BY sorts results sets

A. example:
SELECT c l m _ a e C U T o u n n m ) as m c u t o u n n m , O N (c l m _ a e yon FROM t b e n m ORDER BY m c u t [ASC | DESC] al_ae yon

B. ORDER BY can have mulitple arguments


SELECT c l ,c l ,c l FROM t b e ORDER BY c l , c l oA oB oC al1 oB oC and you can add in the direction of the sort SELECT c l ,c l ,c l FROM t b e ORDER BY c l ASC, c l DESC oA oB oC al1 oB oC

C. ORDER BY will also take a number specifying which columns to sort by. In this case the second and third, so it would be colB and colC.
SELECT c l ,c l ,c l FROM t b e ORDER BY 2, 3 oA oB oC al1

D. example:

www.fincher.org/tips/General/SQL.shtml

17/38

9/3/12

SQL Examples
SELECT m m e _ o o n o n (m m e _ o e b r n ,l a =c u t e b r n ) FROM l a h s onit GROUP BY m m e _ o ebrn HAVING c u t e b r n ) > 50 o n (m m e _ o mme_ola ebrn on --------- ----------2 442 3 130 4 104 5 260 6 78

E. Another Example
SELECT m m e _ o ebrn, date=l a h s .o t d t , onit u_ae f n =l a h s .f n _ s e s d ie onit ieasse, p i =l a h s .f n _ a d ad onit iepi FROM l a h s onit WHERE (m m e _ o BETWEEN 100 AND 150) AND (f n _ s e s d - I N L (f n _ a d > 0) ebrn ieasse S U L i e p i ,0) ORDER BY m m e _ o ebrn COMPUTE s m i e p i ), s m i e a s s e ) BY m m e _ o u (f n _ a d u (f n _ s e s d ebrn

8. JOINs - We are all family here


Joins allow you to retrieve columns from two or more tables usually within the same database, but also among different databases.

A. Two types of JOINs ANSI - Join Operators: INNER JOIN, CROSS JOIN, LEFT/RIGHT/FULL OUTER JOIN SQL Server - Join Operators: =,<>, *= and =* B. Examples of SQL Server
SELECT p b n m , t t e u_ae il FROM t t e ils INNER JOIN p b i h r --Note: INNER is optional ulses ON t t e .p b i = p b i h r .p b i ils u_d ulses u_d SELECT p b n m , t t e u_ae il FROM t t e , p b i h r ils ulses WHERE t t e .p b i = p b i h r .p b i ils u_d ulses u_d

Join Types and estimated usage from Joe Temborius:


% use Join T p s ye 90 Inner 0 Cross 6 Outer 1 Sl ef 3 Uin no

C. Example of ANSI INNER JOIN


SELECT s o _ a e q y t t e trnm, t, il FROM t t e ils INNER JOIN s l s ae ON t t e .t t e i = s l s i l _ d ils il_d a e .t t e i INNER JOIN s o e trs ON s o e .s o _ d = s l s t r i trs tri a e .s o _ d

D. Example of multiple ANSI INNER JOIN


SELECT c .i b , o sn c .c p _ o o oyn, c .o _ o n o nla, t .t t e i il, t .a t o , i uhr i .language, t i .c v r t oe, i .l a a l t onbe FROM t t e t il i

www.fincher.org/tips/General/SQL.shtml

18/38

9/3/12

SQL Examples
INNER JOIN c p c oy o ON t .t t e n = c .t t e n i il_o o il_o INNER JOIN i e i tm t ON i .t t e n = c .t t e n t il_o o il_o WHERE c .i b = 1500 OR c .I B = 1000 o sn o SN ORDER BY c .i b o sn

E. Example of LEFT OUTER JOIN


SELECT m m e .m m e _ o ebr ebrn, l s n m ,f r t a e i d e n t a , a t a e i s n m ,m d l i i i l ib, sn lgdt o_ae FROM m m e LEFT OUTER JOIN r s r a i n ebr eevto ON m m e .m m e _ o = r s r a i n e b r n ebr ebrn e e v t o .m m e _ o WHERE m m e .m m e _ o = 340 OR m m e .m m e _ o = 341 ebr ebrn ebr ebrn ORDER BY m m e .m m e _ o ebr ebrn

F. Example of SQLServer Join


SELECT m m e _ o , c u t FROM r s r a i n ebrn o n (*) eevto WHERE i b IN sn (SELECT i e .i b tm sn FROM t t e il JOIN i e tm ON t t e i l _ o = i e .t t e n i l .t t e n tm il_o WHERE t t e LIKE " P o r m e % ) il %rgamr" group by m m e _ o ebrn

G. A small example of joins given:


CREATE TABLE t b e al1 ( mky ye int NOT NULL , lte1 etr char(1) NOT NULL, ) INSERT INTO t b e (m k y e t r ) VALUES (1,' ' a l 1 y e ,l t e 1 a) INSERT INTO t b e (m k y e t r ) VALUES (2,' ' a l 1 y e ,l t e 1 b) INSERT INTO t b e (m k y e t r ) VALUES (3,' ' a l 1 y e ,l t e 1 c) CREATE TABLE t b e al2 ( mky ye int NOT NULL , lte2 etr char(1) NOT NULL, ) INSERT INTO t b e (m k y e t r ) VALUES (1,' ' a l 2 y e ,l t e 2 d) INSERT INTO t b e (m k y e t r ) VALUES (2,' ' a l 2 y e ,l t e 2 e) INSERT INTO t b e (m k y e t r ) VALUES (4,' ' a l 2 y e ,l t e 2 g)

which creates two tables:


TABLE: table1 mykey letter1 [int(10)] [char(1)] 1 2 3 a b c

TABLE: table2 mykey letter2 [int(10)] [char(1)] 1 2 4 d e g

H. More Examples of JOINs


a. INNER JOIN - connects only the common rows. SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 1 y e ,t b e .l t e 1 a l 2 e t r

www.fincher.org/tips/General/SQL.shtml

19/38

9/3/12

SQL Examples
FROM t b e al1 INNER JOIN t b e al2 ON t b e .m k y = t b e .m k y al1 ye al2 ye wihpoue: hc rdcs mky ye lte1lte2 etr etr ----------- ------- ------1 a d 2 b e b. CROSS JOIN - creates the cartesian product (all possible combinations) SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 1 y e ,t b e .l t e 1 a l 2 e t r FROM t b e al1 CROSS JOIN t b e al2 wihpoue: hc rdcs mky ye lte1lte2 etr etr ----------- ------- ------1 a d 1 a e 1 a g 2 b d 2 b e 2 b g 3 c d 3 c e 3 c g c. OUTER JOIN - three types i. LEFT OUTER JOIN - selects all valid rows from the first table SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 1 y e ,t b e .l t e 1 a l 2 e t r FROM t b e al1 LEFT OUTER JOIN t b e al2 ON t b e .m k y = t b e .m k y al1 ye al2 ye ii. RIGHT OUTER JOIN - selects all valid rows from the second table SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 1 y e ,t b e .l t e 1 a l 2 e t r FROM t b e al1 RIGHT OUTER JOIN t b e al2 ON t b e .m k y = t b e .m k y al1 ye al2 ye mky ye lte1lte2 etr etr ----------- ------- ------1 a d 2 b e (null) (null) g iii. FULL OUTER JOIN - selects all matching rows from both SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 1 y e ,t b e .l t e 1 a l 2 e t r FROM t b e al1 F L OUTER JOIN t b e UL al2 ON t b e .m k y = t b e .m k y al1 ye al2 ye mky ye lte1lte2 etr etr ----------- ------- ------1 a d 2 b e 3 c (null) (null) (null) g

d. Multiple OUTER JOINs CREATE TABLE t b e al3 ( mky ye int NOT NULL , lte3 etr char(1) NOT NULL, ) INSERT INTO t b e (m k y e t r ) VALUES (1,' ' a l 3 y e ,l t e 3 d)

www.fincher.org/tips/General/SQL.shtml

20/38

9/3/12

SQL Examples
INSERT INTO t b e (m k y e t r ) VALUES (2,' ' a l 3 y e ,l t e 3 e) INSERT INTO t b e (m k y e t r ) VALUES (5,' ' a l 3 y e ,l t e 3 h) T e w execute, hn e SELECT t b e .m k y a l 1 e t r ,t b e .l t e 2 a l 3 e t r a l 1 y e ,t b e .l t e 1 a l 2 e t r ,t b e .l t e 3 FROM t b e al1 F L OUTER JOIN t b e ON t b e .m k y = t b e .m k y UL al2 al1 ye al2 ye F L OUTER JOIN t b e ON t b e .m k y = t b e .m k y UL al3 al1 ye al3 ye Wihyed: hc ils mky ye lte1lte2lte3 etr etr etr ----------- ------- ------- ------1 a d d 2 b e e 3 c (null) (null) (null) (null) g (null) (null) (null) (null) h

9. JOIN on NULL
SQL Server considers a NULL to be ambiguous, so one NULL is not the same as another NULL. You can force a JOIN if you know the NULLs should match by using something like "(c.color = p.color OR (c.color IS NULL AND p.color IS NULL))". CREATE TABLE c l r ( oos ta em varchar(16) NOT NULL, clr oo varchar(32) NULL, ) CREATE TABLE p i t ( ons clr oo varchar(32) NULL, pit ons int ) INSERT INTO c l r VALUES (' o s e s ,' e ' oos lbtr' rd) INSERT INTO c l r VALUES (' w n ' w i e ) oos s a s ,' h t ' INSERT INTO c l r VALUES (' e l f s ' oos j l y i h ,NULL) INSERT INTO p i t VALUES (' e ' ons r d ,100) INSERT INTO p i t VALUES (' h t ' ons w i e ,90) INSERT INTO p i t VALUES (NULL,80) ons SELECT * FROM c l r c JOIN p i t p ON c o o = p o o oos ons .c l r .c l r -- returns: --lobsters red red 100 --swans white white 90 SELECT * FROM c l r c JOIN p i t p ON (c o o = p o o OR (c o o IS NULL AND p o o IS oos ons .c l r .c l r .c l r .c l r -- returns: --lobsters red red 100 --swans white white 90 --jellyfish NULL NULL 80

10. Subqueries
A. Three ways to connect queries with subqueries
a. =,>,< ... b. IN c. EXISTS

B. Example 1
--This is a 'classic' subquery. --Show all titles that have a price --larger than average of all titles. USE p b us SELECT p i e t t e rc, il FROM t t e ils WHERE p i e > rc (SELECT A G r c ) FROM t t e ) V (p i e ils

C. Example 2
SELECT t t e i AS T t e il_d il, q y AS Q a t t , t uniy

www.fincher.org/tips/General/SQL.shtml

21/38

9/3/12

SQL Examples
(SELECT S M t ) FROM s l s AS ' o a S l s , U (q y ae) Ttl ae' (CONVERT(m n y t )/(SELECT S M t ) FROM s l s o e ,q y U (q y a e ))*100 AS ' o T t l % f oa' FROM s l s ae

D. Example 3
SELECT t t e i , t t e il_d il FROM t t e ils WHERE t t e i IN il_d (SELECT t t e i FROM s l s il_d ae)

11. Triggers
Triggers are bits of code that are executed when an operation occurs on a table. Triggers can be set for INSERT,UPDATE, or DELETE

A. Example
CREATE TRIGGER d l r g eti ON e p m FOR DELETE AS DECLARE @ u r n u e VARCHAR(30) cretsr SELECT @ u r n u e = ' o r , ' + U E _ A E cretsr Sry S R N M () PRINT @ u r n u e cretsr PRINT ' m l y e c n ' b d l t d ' Epoes a't e eee! ROLLBACK TRANSACTION GO

B. Example - get info about a trigger


SELECT n m , c d t ae rae FROM s s b e t yojcs WHERE type = ' R T' EXECUTE s _ e p e t d l r g -- show code, if not encrypted phltx eti EXECUTE s _ e e d d l r g -- what tables does it affect pdpns eti

C.

drop trigger IF EXISTS ( SELECT n m FROM s s b e t WHERE ae yojcs type = ' R AND n m = ' e b r i s r ' ) DROP TRIGGER T' ae mme_net mme_net ebrisr

D. an INSERT trigger creates a special table, called 'inserted' with the inserted row DELETE triggers create 'deleted' with the deleted rows These tables can be queried. E. to create your own messages -- sp_addmessage (>50000) F. sp_configure 'nested triggers',0 -- prevents cascading triggers G. Example:
CREATE TRIGGER m m e _ n e t ebrisr ON m m e ebr FOR INSERT AS /* ** Don't allow duplicate primary k eys. ** This is normally done via a unique ** index rather than a trigger. It is ** included here just as an example. */

IF (SELECT c u t o n (*) FROM m m e , i s r e ebr netd WHERE m m e .m m e _ o = i s r e .m m e _ o > 1 ebr ebrn netd ebrn) BEGIN RAISERROR (' r n a t o w l n t b p o e s d T o m m e s c n o h v t e s m m m e _ o ' Tascin il o e rcse. w ebr ant ae h ae ebrn. ROLLBACK TRANSACTION END ELSE

www.fincher.org/tips/General/SQL.shtml

22/38

9/3/12
H. Example:
/* ** ** ** ** */

SQL Examples

Auto generate a primary k ey value, if needed (A zero got in there because it is the default; ie, the user did not enter a member number.) Work s only if one row at a time is being added.

IF (SELECT c u t o n (*) FROM m m e ebr WHERE m m e .m m e _ o = 0) > 0 ebr ebrn BEGIN UPDATE m m e ebr SET m m e _ o = (SELECT m x e b r n ) FROM m m e ) + 1 ebrn a (m m e _ o ebr WHERE m m e _ o = 0 ebrn END GO

12. Data Integrity/IDENTITY


An identity forces SQL server to have a unique value in a field. The starting value and the increment value can be set as follows CREATE TABLE s o e 2 trs ( s o _ d int i e t t (1000,10) NOT NULL , -- starts at 1000, increments by 10 tri dniy s o _ a e varchar (40) NULL , trnm )

To s e t e values o t e e e h f hs,

SELECT I E T S E (' l s ' I E T I C (' l s ' -- shows initial identity and increment D N _ E D c a s ), D N _ N R c a s )

13. to set directly an IDENTITY field (for testing etc to override defaults)
SET I E T T _ N E T [T b e a e ON DNIYISR alNm] Example: SET I E T T _ N E T P b ..c a s ON -- allows an identity to be inserted DNIYISR us ls

14. IDENTITYCOL is a keyword which substitues for the name of the identity column
SELECT M X D N I Y O ) FROM s o e 2 A (I E T T C L trs -- identitycol is a k eyword refering to a tables' identity column

-- Defining constraints Primary Key Unique Foreign Key Default Check in s s o m n s a field c l e ' e t c n a n y u c n t a t ycmet ald tx' otis or osris s _ e p o s r i t or s _ e p <t b e a e -- more friendly phlcntan phl alnm>

15. Comments
C m e t a e s r o n e with ' * and ' / , b t c n o , for s m omns r urudd /' *' u ant oe bzaerao cnana'O cmad izr esn oti G' omn.

www.fincher.org/tips/General/SQL.shtml

23/38

9/3/12

SQL Examples
E e y h n a t r a ' - is a c m e t vrtig fe -' omn

16. CONSTRAINTs
Constraints can be set on the value of valid fields. CREATE TABLE T l l l ( b_v I e C d CHAR(6) NOT NULL, tmoe U i C s S A L O E NOT NULL, ntot MLMNY U i P i e S A L O E NOT NULL, ntrc MLMNY CNTAN pieif OSRIT rcdf CHECK (U i P i e > U i C s ) ) GO ntrc ntot

17. Constraints can be named


CREATE TABLE P y o l arl ( E p o CHAR(3) NOT NULL, mn C e k o CHAR(10) NOT NULL hcn CNTAN UCeko OSRIT _hcn UNIQUE N N L S E E (c e k o O C U T R D h c n ), P y a e SMALLDATETIME NOT NULL adt CNTAN D_adt OSRIT FPyae DEFAULT G T A E E D T (), A o n S A L O E NOT NULL mut MLMNY CNTAN C_mut OSRIT KAon CHECK (A o n BETWEEN 10000 AND 100000), mut CNTAN P_arl OSRIT KPyol PRIMARY KEY C U T R D LSEE (e p o h c n ,p y a e m n ,c e k o a d t ) WITH F L F C O =25, ILATR CNTAN F_arl OSRIT KPyol FOREIGN KEY (e p o REFERENCES e p (e p o mn) m mn) ) -- must drop constraint before index IF EXISTS (SELECT n m FROM s s b e t WHERE n m = ' e b r i e t ) ae yojcs ae mme_dn' ALTER TABLE m m e ebr DROP C N T A N m m e _ d n OSRIT ebriet IF EXISTS (SELECT n m FROM s s n e e WHERE n m = ' e b r i e t ) ae yidxs ae mme_dn' DROP INDEX m m e .m m e _ d n ebr ebriet ALTER TABLE m m e ebr ADD C N T A N m m e _ d n PRIMARY KEY C U T R D (m m e _ o WITH F L F C O = 90 OSRIT ebriet LSEE ebrn) ILATR

18. Constraints can set a default value:


IF EXISTS (SELECT n m FROM s s b e t WHERE n m = ' t t _ e a l ' ae yojcs ae saedfut) ALTER TABLE a u t dl DROP C N T A N s a e d f u t OSRIT tt_eal GO ALTER TABLE a u t dl ADD C N T A N s a e d f u t DEFAULT ' A FOR s a e OSRIT tt_eal W' tt GO to add a primary key restaint: alter table m t b e ADD primary key (m k y d m o h r o u n yal yei, yteclm)

19. Views
CREATE VIEW a t o l s uhrit (A t o N m , L c t o ) uhrae oain AS SELECT SUBSTRING(a _ n m + ' ' + a _ n m ,1,25), ufae ulae SUBSTRING(c t + ' ' + s a e + ' ' + z p iy , tt i ,1,25)

www.fincher.org/tips/General/SQL.shtml

24/38

9/3/12
FROM a t o s uhr GO

SQL Examples

SELECT * FROM a t o l s uhrit --- see your views: SELECT n m , c d t ae rae FROM s s b e t yojcs WHERE type = ' ' V -- to see your source code for the view EXECUTE s _ e p e t A t o L s phltx uhrit EXECUTE s _ e e d A t o L s -- list tables needed for this view pdpns uhrit CREATE VIEW M n g r aaes WITH E C Y T O NRPIN AS SELECT e p o e p a e t t e mn, mnm, il FROM e p m WHERE t t e M N G R i l =' A A E ' WITH CHECK OPTION -- updates/inserts into this view must satisfy WHERE clause GO SELECT * FROM m n g r aaes s_epetmngr phltx aaes

--This should fail the CHECK INSERT INTO m n g r aaes VALUES (' 9 ' ' A E , B L ' ' C ' -- fails because MCT != MANAGER 99, GTS IL, MT) Wa SriePcsde m SLSre hv isald ht evc ak os y Q evr ae ntle? ty r SELECT @ v r i n @eso

CREATE VIEW with JOIN

create view s m a y umr as select R l I , S a e o d r P o u t y e Language, L n u g C d , M a u e a e A s s m n , A c p a c T ued tkhle, rdcTp, agaeoe esrNm, seset cetne from R l s r ue join M a u e m on r e s r I = m e s r I esrs .M a u e D .M a u e d join T p s t on t y e D = r y e D ye .T p I .T p I join L n u g s l on l a l S f i = t agae .T b e u f x .Language

20. OBJECT_ID()
A. How to conditionally delete a view
-- old style IF EXISTS ( SELECT n m FROM s s b e t ae yojcs WHERE type = ' ' AND n m = ' t f ' ) V ae suf DROP VIEW s u f tf -- new style IF O J C _ D s u f , ' ' IS NOT NULL B E T I (' t f ' V ) DROP VIEW s u f tf go -- another way IF O J C P O E T (o j c _ d d o s u f ), N I V e ' = 1 B E T R P R Y b e t i (' b . t f ' ' s i w ) drop view s u f tf go

B. How to conditionally delete a table


IF O J C _ D t a f c d t ' ' ' IS NOT NULL B E T I (' r f i _ a a , U ) DROP TABLE t a f c d t rfi_aa GO

www.fincher.org/tips/General/SQL.shtml

25/38

9/3/12

SQL Examples
C. Common second parameters to OBJECT_ID()
/* C = CHECK constraint D = DEFAULT (constraint or stand-alone) F = FOREIGN KEY constraint PK = PRIMARY KEY constraint P = SQL stored procedure FN = SQL scalar function U = Table (user-defined) UQ = UNIQUE constraint V = View X = Extended stored procedure */

21. Isolation levels via Table Hints


If the results of your queries do not always have to be perfect, you can increase query speed and reduce contention by using "READ UNCOMMITTED" or "WITH(NOLOCK)", which does not lock a table during a SELECT and allows "dirty" reads. This is dangerous, but in certain situations can be advantageous. SELECT C U T FROM d o u h r WITH(N L C ) O N (*) b .A t o s OOK This will not lock the table and make the query faster. Use the following command to make an entire session use no locking SET TRANSACTION I O A I N L V L READ U C M I T D SLTO EE NOMTE GO

22. INDEXs
CREATE INDEX [C U T R D O C U T R D n m ON table (c l ,c l ,...) L S E E |N N L S E E ] a e o1 o2 EXECUTE s _ e p n e e p s o s i f on index phlidx m hw no C T L -- sk ips to next heading NR limit: c m o i e index l n t < 900 c a s opst egh hr

SET S O P A ON -- debug statement to show if indexes are being used HWLN GO SELECT * FROM a t o s uhr WHERE c t = ' e t iy K n ' --table scan SELECT * FROM a t o s uhr WHERE a _ d = ' 2 - 5 6 8 ' --clustered index ui 134-79 SET S O P A O F HWLN F GO --

--------------- OPTIMIZER HINTS -------------SET S O P A ON HWLN GO SELECT a _ n m , a _ n m , p o e ulae ufae hn FROM a t o s (INDEX = 1) -- INDEX=0 is none, INDEX=indexname uhr WHERE a _ n m = ' m t ' ulae Sih SET S O P A O F HWLN F GO

--------------- UPDATE STATISTICS -- updates statistics that the optimizer uses to d t r i e w i h index to use on a q e y eemn hc ur ---------------Plug in a value for TABLENAME

www.fincher.org/tips/General/SQL.shtml

26/38

9/3/12

SQL Examples
SELECT ' n e N m ' = s s n e e .n m , Idx ae yidxs ae ' t t s i s D t ' = S A S D T (s s n e e .i , s s n e e .i d d Saitc ae TT_AE yidxs d yidxs ni) FROM s s b e t , s s n e e yojcs yidxs WHERE s s b e t .n m = ' u h r ' yojcs ae atos AND s s b e t .i = s s n e e .i yojcs d yidxs d UPDATE S A I T C a t o s TTSIS uhr -- show fragmentation DECLARE @ b INT tl SELECT @ b = O J C _ D s l s ) tl B E T I (' a e ' D C S O C N I (@ b ) BC HWOTG tl

------------- check databases D C C E K B -- should be run once a week on all database, BC HCD -- should be done before a back up -d i y - d m database, update s a i t c on all i d x s al up ttsis nee h u l - d m transaction l g ory up o w e l - drop and r c e t i d x s eky erae nee -- show performance data SET S O P A ON -- shows indexes being used HWLN SET S A I T C I ON TTSIS O SET S A I T C TIME ON -TTSIS

-- drop an index if it exists IF EXISTS (SELECT n m FROM s s n e e WHERE n m = ' e e v _ t m l n ' ae yidxs ae rsreie_ik) DROP INDEX r s r a i n e e v _ t m l n e e v t o .r s r e i e _ i k GO -- example of showing the elapsed time DECLARE @ e s g char(255) DECLARE @ e a datetime msae bgn SELECT @ e a = G T A E bgn E D T ()

CREATE UNIQUE INDEX r s r e i e t ON r s r a i n (m m e _ o i b ) eev_dn eevto ebrn, sn WITH F L F C O = 75 ILATR CREATE INDEX r s r e i e _ i k ON r s r a i n (i b ) eev_tmln eevto sn SELECT @ e s g = ' i e ( n m n t s s c n s t c e t r s r a i n r l t d i d x s ' msae Tm i iue:eod) o rae eevto eae nee. + CONVERT( char(2), D T D F (s ,@ e a ,G T A E A E I F s b g n E D T ())/60 ) + ' ' : + CONVERT( char(2), D T D F (s ,@ e a ,G T A E A E I F s b g n E D T ())%60 ) PRINT @ e s g msae GO

23. System Variables


SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT SELECT 'oncin: Cnetos ' @oncin ,@ c n e t o s 'P Bs CU uy ' @p_uy ,@ c u b s 'usrRw Cro os ' @usrrw ,@ c r o _ o s 'BS DT ' @bs ,@ d t 'ro Err ' @ro ,@ e r r 'ec Sau Fth tts ' @ec_tts ,@ f t h s a u 'dniy Iett ' @dniy ,@ i e t t 'de Il ' @de ,@ i l 'OBs I uy ' @obs ,@ i _ u y 'agaeI Lnug D ' @agd ,@ l n i 'agae Lnug ' @ ,@ language 'a Cnetos' @a_oncin M x o n c i n ,@ m x c n e t o s 'a Peiin ' @a_rcso Mx rcso ,@ m x p e i i n 'SVrin M eso ' @irsfvrin ,@ m c o o t e s o 'etLvl Ns ee ' @etee ,@ n s l v l 'pin Otos ' @pin ,@ o t o s 'akRcie Pc eevd ' @akrcie ,@ p c _ e e v d 'akSn Pc et ' @aksn ,@ p c _ e t 'aktErr Pce ros ' @akterr ,@ p c e _ r o s 'rcdr I Poeue D ' @rcd ,@ p o i 'o Cut Rw on ' @ o c u t -- how many rows were effected on last operation ,@ r w o n 'evrNm Sre ae ' @evrae ,@ s r e n m 'evc Nm Srie ae ' @evcnm ,@ s r i e a e 'PD SI ' @pd ,@ s i 'etSz Tx ie ' @etie ,@ t x s z 'ieTcs Tm ik ' @ieik ,@ t m t c s

www.fincher.org/tips/General/SQL.shtml

27/38

9/3/12
SELECT SELECT SELECT SELECT SELECT

SQL Examples
'oa Err Ttl ros 'oa Ra Ttl ed 'oa Wie Ttl rt 'rnCut Ta on 'eso Vrin ' @oa_ros ,@ t t l e r r ' @oa_ed ,@ t t l r a ' @oa_rt ,@ t t l w i e ' @rnon ,@ t a c u t ' @eso ,@ v r i n

24. BCP bulk copy


rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e rm e

BPEO A C D M .B T T i b t h f l e p r s all A T O S FROM t e hs ac ie xot UHR h P B database to a A C I f l c l e R S L S X US n S I i e a l d E U T .T T /c i d c t s ' h r c e ' f r a v . /n for ' a i e f r a niae caatr omt s ntv' omt /t i d c t s t e field t r i a o (default is T B niae h emntr A) /S i d c t s t e S r e to c n e t to niae h evr onc /U i d c t s t e L g n I niae h oi D /P is t e p s w r (if a y h asod n) Type in B P with n o t o s to s e p r m t r s m a y C o pin e aaee umr A t r y u r n t i , go into N T P D and fe o u hs OEA check o t t e r s l s in ' e u t . x ' u h eut rslstt *** CHANGE S R E N M B L W B F R R N I G *** EVR AE EO EOE UNN

b p p b .d o u h r o t r s l s x /c /t | /S t d n x /U a /P c u s b .a t o s u e u t .t t "" suet s

25. EXTENDED STORED PROCEDURES


--Display all 'registered' ESP's EXECUTE s _ e p x e d d r c phletnepo -- to get the last inserted identity INSERT R s o d n s (t s ) VALUES (' ' SELECT @ I E T T epnet et N) @DNIY ---- misc xp_* USE m s e atr GO --Display all devices EXECUTE x _ m s e l ' i c \ s q \ a a * d t / s pcdhl dr :msldt\.a o' PRINT ' ' --Send a message to the NT Event Log EXECUTE x _ o e e t 60000, ' t p s g - w r t k n ! , e r r plgvn So in os id' ro PRINT ' ' --Show current NT accounts that can access SQL Server EXECUTE x _ o i i f plgnno PRINT ' ' --Display current SQL Server version and build info EXECUTE x _ s e pmvr PRINT ' ' --Display all local NT groups EXECUTE x _ n m r u s peugop

26. UNDOCUMENTED ESP's


--XP_REGREAD allows you to read Registry Key values SET N C U T ON OON GO DECLARE @ r VARCHAR(50) og DECLARE @ w VARCHAR(50) on EXECUTE x _ e r a ' K Y L C L M C I E , prged HE_OA_AHN' 'OTAEMCOOTMSLEVRMSLEVRCreteso' SFWR\IRSF\SQSRE\SQSRE\urnVrin, ' e i t r d r a i a i n ,@ a a = @ r o t u RgseeOgnzto' prm og upt

www.fincher.org/tips/General/SQL.shtml

28/38

9/3/12

SQL Examples
EXECUTE x _ e r a ' K Y L C L M C I E , prged HE_OA_AHN' 'OTAEMCOOTMSLEVRMSLEVRCreteso' SFWR\IRSF\SQSRE\SQSRE\urnVrin, 'eitrdwe' prm= @w otu R g s e e O n r ,@ a a on upt PRINT ' h e e s t u S L S r e f r t i c a s t p d t e e i : Wovr e p Q evr o hs ls ye hs n' PRINT ' ' SELECT ' e i t r d O g n z t o i ' R g s e e r a i a i n s +UPPER(@ r ) og SELECT ' e i t r d O n r i Rgsee we s ' +UPPER(@ w ) on SET N C U T O F OON F GO -->

27. CURSORS
Cursors allow an entire result set to be captured and manipulted as a single piece of data. ******************************************************DECLARE @ u r n v l e char(32) cretau DECLARE m c r o C R O FOR yusr USR SELECT distinct m v l e FROM m t b e yau yal OPEN m c r o yusr F T H N X FROM m c r o INTO @ u r n v l e EC ET yusr cretau WHILE (@ f t h s a u = 0) @ec_tts -- while OK BEGIN print @ u r n v l e cretau exec(' E E T m c l m F O ' + @ u r n v l e ) -- some useful work SLC youn RM cretau F T H N X FROM m c r o INTO @ u r n v l e EC ET yusr cretau END CLOSE m c r o yusr DEALLOCATE m c r o yusr GO ******************************************************--Count the number of members that have --a 'J' as a middle initial value USE L b a y irr SET N C U T ON OON DECLARE @ i a u char(1) mvle DECLARE @ o n e int cutr DECLARE @ t c u t r char(50) srone SELECT @ o n e =0 cutr DECLARE m c u t C R O FOR ion USR SELECT m d l i i i l FROM m m e identa ebr OPEN m c u t ion F T H N X FROM m c u t EC ET ion INTO @ i a u m v l e -- move to first row WHILE (@ f t h s a u = 0) @ec_tts BEGIN -- while OK

IF @ i a u = ' ' SELECT @ o n e = @ o n e + 1 mvle J cutr cutr F T H N X FROM m c u t EC ET ion INTO @ i a u mvle END CLOSE m c u t ion DEALLOCATE m c u t ion SELECT @ t c u t r = ' u b r o J i i i l : +CONVERT(char(10),@ o n e ) srone Nme f ntas' cutr PRINT @ t c u t r srone GO -- RAISERROR s _ d m s a e 55555, 16, ' i c s t s m s a e ,u _ n l s ,t u padesg Mth et esg' segih re RAISERROR(55555,16,1)

www.fincher.org/tips/General/SQL.shtml

29/38

9/3/12

SQL Examples

28. Convert a database from local time to utc time.


First we find all constraints defining the default value for the column to be "GETDATE()". Then we drop those constraints, and add the default constraint "GETUTCDATE()" instead. Secondly we go through all the columns and adjust their time from local to UTC. /* Converts all fields with a default value containing "GETDATE()" to "GETUTCDATE()" and updates existing times to utc */ set n c u t on oon declare @ a l N m varchar(255) tbeae declare @ o u n a e varchar(255) clmNm declare @ o s r i t a e varchar(255) cntanNm declare @ e C n t a n N m varchar(255) nwosritae declare @ y r p m varchar(512) mDoCd declare @ y r a e m varchar(512) mCetCd declare @ i e o e o m n varchar(512) tmZnCmad declare @ i e o e f s t int tmZnOfe select @ i e o e f s t = D t d f (h ,G T A E E U C A E tmZnOfe a e i f h E D T (),G T T D T ())

-- original base query from 'MeanOldDBA' at -- http://www.developmentnow.com/g/113_2004_9_0_0_433030/Search-for-defaults-in-table-DDL.htm DECLARE m c r o C R O FOR yusr USR SELECT s 1 a e AS t b e n m , o .n m al_ae s 1 a e AS c l m _ a e c .n m ounnm, s 2 a e AS d f u t n m o .n m eal_ae FROM ssbet s1 yojcs o INNER JOIN s s o u n s 1 ON s 1 d = s 1 d yclms c o .i c .i INNER JOIN s s b e t s 2 ON s 1 d f u t = s 2 d yojcs o c .c e a l o .i INNER JOIN s s o m n s s 2 ON s 2 d = s 2 d ycmet c o .i c .i WHERE s2 c .text LIKE ' g t a e ) ' %edt(% OPEN m c r o yusr F T H N X FROM m c r o INTO @ a l N m , @ o u n a e @ o s r i t a e EC ET yusr tbeae clmNm, cntanNm WHILE (@ f t h s a u = 0) @ec_tts -- while OK BEGIN print ' - T b e ' + @ a l N m + ' C n t a n : ' + @ o s r i t a e ' C l m : ' + @ o u n - al: tbeae , osrit cntanNm+ , oun clm SELECT @ y r p m = ' A T R T B E [ +@ a l N m +' D O C N T A N [ +@ o s r i t a e mDoCd LE AL ' tbeae ] RP OSRIT ' cntanNm PRINT @ y r p m mDoCd EXECUTE (@ y r p m ) mDoCd SELECT @ e C n t a n N m = ' F ' t b e a e _ t m _ t ' nwosritae D _ +@ a l N m +' d i e u c SELECT @ y r a e m = ' A T R T B E [ +@ a l N m +' A D C N T A N [ +@ e C n t a n N m mCetCd LE AL ' tbeae ] D OSRIT ' nwosritae PRINT @ y r a e m mCetCd EXECUTE (@ y r a e m ) mCetCd select @ i e o e o m n = ' U D T ' + @ a l N m + ' S T ' + @ o u n a e + ' = D T A D H tmZnCmad PAE tbeae E clmNm AED(O PRINT @ i e o e o m n tmZnCmad EXECUTE (@ i e o e o m n ) tmZnCmad F T H N X FROM m c r o INTO @ a l N m , @ o u n a e @ o s r i t a e EC ET yusr tbeae clmNm, cntanNm END CLOSE m c r o yusr DEALLOCATE m c r o yusr GO

29. Misc Tips


A. When SQLServer UPDATEs a row, it really deletes i replaces it with a new one
SELECT t t e o y n ,d e d t ,D T D F (D Y u _ a e E D T ()) FROM o e d e i l ,c p _ o u _ a e A E I F A ,d e d t ,G T A E vru WHERE D T D F (D Y u _ a e E D T ()) > 14 A E I F A ,d e d t ,G T A E

B. How to convert a varchar column to nvarchar?


You can convert a column in place. ALTER TABLE M T b e a e ALTER COLUMN [M C l m N m ] N A C A (3000) yalNm younae VRHR

C. Finding gaps in a sequence


This finds any non-consecutive numbers in the userID column. SELECT A s r D + 1 .u e I FROM S R s o d n s AS A Depnet WHERE NOT EXISTS ( SELECT B s r D FROM S R s o d n s AS B .u e I Depnet WHERE A s r D + 1 = B s r D .u e I .u e I )

www.fincher.org/tips/General/SQL.shtml

30/38

9/3/12

SQL Examples
GROUP BY A s r D .u e I ;

D. Set a database to single use only.


This is useful in simulating database failure to stop general access to a database. EXECUTE s _ b p i n l b a y ' b u e o l ' T U -- dbo user only pdoto irr, do s ny, RE EXECUTE s _ b p i n l b a y ' b u e o l ' F L E pdoto irr, do s ny, AS

or
alter database m D t b s N m set S N L _ S R WITH ROLLBACK I M D A E yaaaeae IGEUE MEIT alter database m D t b s N m set M L I U E yaaaeae UT_SR

E. User Defined Datatypes (UDDT)


EXECUTE s _ d t p z p o e ' h r 1 ) padye icd, ca(0' EXECUTE s _ d t p p o e u b r ' h r 1 ) , NULL padye hnnme, ca(3' EXECUTE s _ r p y e <t p n m > -- to get rid of it pdotp yeae to get a list of UDDT s_ep phl example: CREATE TABLE m m e ( ebr m m e _ o m m e _ o NOT NULL, -- member_no is a User Defined Data Type ebrn ebrn l s n m s o t t i g NOT NULL, atae hrsrn f r t a e s o t t i g NOT NULL, isnm hrsrn m d l i i i l l t e NULL, identa etr p o o r p i a e NULL htgah mg )

USE M s e Atr EXECUTE s _ b p i n m d , ' r n . l g o c k t ' r e p d o t o y b t u c o n h p . ,t u to set SELECT into/b l c p ukoy EXECUTE s _ b p i n m d , ' E E T i t / u k o y ,t u pdoto yb SLC noblcp' re chars are treated as varchar's if NULL is a possible value. Binary Large OBject - BLOB SET N C U T ON OON SET N C U T O F OON F --suppress 'rows affected' msg

F. Logic don't use "= NULL" use "IS NULL" because its ANSI NULLs fail all comparisons "NULL = NULL" is false Order of Presedence: (),NOT,AND,OR G. the EXECUTE command can be used to build commands from parts H. Example 1
create p o d s l y a l rc ipatbe @ b varchar(30) tl as EXECUTE (' E E T * F O ' + @ b ) SLC RM tl

I. Example 2
SELECT @ m = " r a e d t b s " p o a b e +" O " d t d v c +" = 6 L G O " l g e i e cd c e t a a a e +@ r j b r v N +@ a a e i e O N +@ o d v c SELECT @ m cd EXECUTE (@ m ) cd

J. Terms:
A batch is a set of one or more SQL statements submitted together and executed as a single group. A script is a series of one or more batches submitted one after the other. A script

www.fincher.org/tips/General/SQL.shtml

31/38

9/3/12

SQL Examples
is a file, with a default extension of .SQL Comparison operators (=,<>,>,<,>=,<=), BETWEEN, IN, LIKE, IS NULL, and IS NOT NULL

K. The System supplied databases.


Database Function Master: Model: Msdb: Tempdb: pubs: Controls all user databases and SQL Server as a whole Serves as a template when creating new user databases Provides support for the SQL Executive service Used for temporary working storage for all connections A sample database

2. A l c t o U i : 1/2 B i c e e t o database s o a e s a e loain nt M nrmns f trg pc E t n : E g t 2 p g s o table or index s o a e s a e xet ih K ae f trg pc P g : T e b s c u i o I in S L S r e (2 in s z ) a e h a i n t f /O Q evr K ie

L. Cursors
--deleteViews -- This deletes all views which start with an X -- trivial example of using cursors in sql server 6.5 IF EXISTS ( SELECT n m FROM s s b e t ae yojcs WHERE type = ' ' AND n m = ' e e e i w ' ) P ae dltVes DROP P O E U E d l t V e s RCDR eeeiw go ******************---------------GO CREATE P O E U E d l t V e s RCDR eeeiw @ a a a e a e varchar(30) dtbsnm AS DECLARE @ i w a e S S A E venm YNM, @ q s CHAR(255), sl @ u l i w a e CHAR(255) flvenm SELECT @ q s = ' E L R v e _ u s r C R O F R S L C n m F O ' sl DCAE iwcro USR O EET ae RM + @aaaeae+ '.yojcsWEEtp ='v'adnm LK 'X' ' dtbsnm .ssbet HR ye '' n ae IE '%' -exec(@ q s sl) OPEN v e _ u s r iwcro F T H N X FROM v e _ u s r INTO @ i w a e EC ET iwcro venm WHILE (@ F T H S A U =0) @EC_TTS BEGIN SELECT @ u l i w a e = @ a a a e a e + ' . + @ i w a e flvenm dtbsnm .' venm SELECT ' u r n v e n m i ' + @ u l i w a e cret iwae s flvenm --EXEC ('DROP VIEW ' + @fullviewname) F T H N X FROM v e _ u s r INTO @ i w a e EC ET iwcro venm END CLOSE v e _ u s r iwcro DEALLOCATE v e _ u s r iwcro GO

M. Get all the column names in a table


SELECT n m FROM s s o u n WHERE i in (SELECT i FROM s s b e t ae yclms d d yojcs where n m = ' y o u n ) ae mclm'

N. Easy way is to access meta data is the 'information_schema' view:


SELECT * FROM i f r a i n s h m .columns nomto_cea

O. How to restore a database FROM a .BAK file


RSOEFLLSOL ETR IEITNY

www.fincher.org/tips/General/SQL.shtml

32/38

9/3/12

SQL Examples
FROM D S = IK ':PormFlsMcootSLSre\SQ$U18BCU\Depnet.a' C\rga ie\irsf Q evrMSLAS5\AKPSRsodnsbk R S O E DATABASE S R s o d n s ETR Depnet FROM D S = IK ':PormFlsMcootSLSre\SQ$U18BCU\Depnet.a' C\rga ie\irsf Q evrMSLAS5\AKPSRsodnsbk WITH M V ' D e p n e t _ a a TO OE SRsodnsDt' ':PormFlsMcootSLSre\SQ$U18Dt\Depnet.d' C\rga ie\irsf Q evrMSLAS5\aaSRsodnsmf, M V ' D e p n e t _ o ' TO OE SRsodnslg ':PormFlsMcootSLSre\SQ$U18Dt\Depnet.d' C\rga ie\irsf Q evrMSLAS5\aaSRsodnslf GO

P. How to retrieve data as xml


Use "FOR XML AUTO" or "FOR XML EXPLICIT" SELECT * FROM s g o p FOR X L A T drus M UO

Q. How to increase the timeout setting


When you get an exception like this: Ecpin Sse.e.eEcpinMsae Teoeainhstmdot xeto: ytmNtWbxeto esg: h prto a ie u You need to increase the timeout setting by opening Enterprise Manager, right clicking on your server and select "Properties", then "Connections", then set "Remote query timeout" to be something larger.

R. Connection Strings
Bad example where password is embedded (but occassionally useful for testing on dev boxes) A p i a i n N m =m A p i a i n Data S u c =m D t b s S r e ; u e i =s ;p s w r =m p s w r plcto ae yplcto; ore yaaaeevr sr d a asod yasod

Real solution where password is not in connection string Data S u c =m D t b s S r e ; T u t d C n e t o =y s database=m D t b s N m ore yaaaeevr rse_oncin e; yaaaeae

S. Working with Devices


Devices are containers for databases and their logs. a. Creating Devices DS II cetsdvcs IK NT rae eie: To create data d v c s y u m s b in m s e . eie o ut e atr D S I I n m =' I R R _ E 1 , IK NT ae LBAYDV' pynm = ':MSLDT\IRR.A' hsae c\SQ\AALBAYDT, v e n = 100, -- must be unique, use sp_helpdevice() dvo -- to find currently used device_number(s) s z = 10240 -- in 2K block s ie DS II IK NT n m =' I R O _ E 2 , ae LBLGDV' pynm = ':MSLDT\IRO.A' hsae c\SQ\AALBLGDT, v e n = 101, dvo s z = 4096 ie b. Resizing Devices -- you can only increase the size of a device, never shrink DISK RESIZE name='MASTER', SIZE=15360 -- size is in 2k pages c. Deleting Devices Note: When using EntepriseManager to drop a device, it does not drop the .DAT file, instead use: sp_dropdevice logical_name [, DELFILE] -- deletes .DAT file too

30. Globally Unique Identifier - GUID


GUIDs are 16 byte binary integers created to be unique identifiers across database instances.

A. Create a GUID
SELECT n w d e i () Produces: B A 5 5 -A 7 -4 8 -8888-0 8 9 8 C 0 31B9 D5 DB D3C431

B. An example

www.fincher.org/tips/General/SQL.shtml

33/38

9/3/12

SQL Examples
We create the first row by using newid() to have sqlserver create the GUID for us, the second row we create by feeding it a GUID directly.

CREATE TABLE g i p a t c udrcie ( gi ud UIUIETFE, NQEDNIIR fae nm VARCHAR(20) NOT NULL, lae nm VARCHAR(30) NOT NULL, ) insert g i p a t c (g i ,f a e n m ) values (n w d A a ' S i h ) u d r c i e u d n m ,l a e e i (),' d m ,' m t ' insert g i p a t c (g i ,f a e n m ) values (' 5 C D 4 8 B - D 5 A F - 2 6 1 2 7 F ,' d m ,' m t ' u d r c i e u d n m ,l a e 87F4-B440-E12B24AF' Aa' Sih select * from g i p a t c udrcie

Produces: D 4 1 F -7178-4 E -8 7 -8 8 7 0 E F A44D D2 C7 61B4C8 8 7 F 4 -8 B -4 0 -A F -2 B 2 4 A F 5CD4 B4 D5 E1 26127F Aa dm Aa dm Sih mt Sih mt

C. You can have sqlserver create Guids by default


CREATE TABLE g i p a t c 2 udrcie ( gi ud U I U I E T F E DEFAULT n w d NQEDNIIR e i (), fae nm VARCHAR(20) NOT NULL, lae nm VARCHAR(30) NOT NULL ) GO INSERT g i p a t c 2 (f a e n m ) VALUES (' d m ,' m t ' udrcie n m ,l a e Aa' Sih) INSERT g i p a t c 2 (f a e n m ) VALUES (' d m ,' m t ' udrcie n m ,l a e Aa' Sih) SELECT * FROM g i p a t c 2 udrcie Produces: gi ud fae nm ------------------------------------ -------------------- -----D A 7 E -3 A -42E9-9 C -0 7 D F 3 4 A a 662B 95 26 CD092D dm 6 9 7 C -9 A -4 7 -8393-1 D 2 0 F 9 A a 0867 24 D8 979414 dm lae nm Sih mt Sih mt

31. Misc SQL Stuff


A. when SQLServer UPDATEs a row, it really deletes it and replaces it with a new one B. DATEDIFF
SELECT t t e o y n ,d e d t ,D T D F (D Y u _ a e E D T ()) FROM o e d e i l ,c p _ o u _ a e A E I F A ,d e d t ,G T A E vru WHERE D T D F (D Y u _ a e E D T ()) > 14 A E I F A ,d e d t ,G T A E

C. Set a database to single use only.


EXECUTE s _ b p i n l b a y ' b u e o l ' T U -- dbo user only pdoto irr, do s ny, RE EXECUTE s _ b p i n l b a y ' b u e o l ' F L E pdoto irr, do s ny, AS

D. Using local variables


You can define local variables with the "@" sign. These are used in parameterized sql commands. DECLARE @ a g varchar(12) ln set @ a g = ' n U ' ln e-K SELECT n m from S T x D f n t o s ae Deteiiin WHERE text LIKE ' b y ' and l n =@ a g %u% ag ln

E. Using LIKE with a scalar variable and wildcards


You need to preface it with the wildcards in separate strings like this DECLARE @ a g varchar(12) ln DECLARE @ e r h r varchar(12) sace set @ a g = ' n U ' ln e-K

www.fincher.org/tips/General/SQL.shtml

34/38

9/3/12

SQL Examples
set @ e r h r = ' u ' sace by SELECT n m from S T x D f n t o s ae Deteiiin WHERE text LIKE ' ' s a c e +' ' and l n =@ a g % +@ e r h r % ag ln

F. Example of declaring a date variable and using DATEADD


DECLARE @ y a e datetime mdt SET @ y a e = ' 0 0 1 - 1 0 : 0 0 . 0 mdt 21-11 00:00' SELECT c u t o n (time) AS ' u b r , a g n m e ' v (time) AS ' i e m ) FROM m T b e tm(s' yal WITH (n l c ) ook WHERE d i e > @ y a e AND d i e < D T A D a ,1,@ y a e tm mdt tm A E D (d y m d t )

G. Example of printing the date with milliseconds (ISO8601)


set @ s = convert(char(25),G T A E mg E D T (),126) -- msg = 2011-11-07T13:08:41.933

H. User Defined Datatypes (UDDT)


EXECUTE s _ d t p z p o e ' h r 1 ) padye icd, ca(0' EXECUTE s _ d t p p o e u b r ' h r 1 ) , NULL padye hnnme, ca(3' EXECUTE s _ r p y e <t p n m > -- to get rid of it pdotp yeae to get a list of UDDT s_ep phl

I. Using a User Defined Type


CREATE TABLE m m e ( ebr m m e _ o m m e _ o NOT NULL, -- member_no is a User Defined Data Type ebrn ebrn l s n m s o t t i g NOT NULL, atae hrsrn f r t a e s o t t i g NOT NULL, isnm hrsrn m d l i i i l l t e NULL, identa etr p o o r p i a e NULL htgah mg )

J. sp_dboption examples
USE M s e atr EXECUTE s _ b p i n m d , ' r n . l g o c k t ' r e p d o t o y b t u c o n h p . ,t u to set SELECT into/b l c p ukoy EXECUTE s _ b p i n m d , ' E E T i t / u k o y ,t u pdoto yb SLC noblcp' re

K. Chars are treated as varchar's if NULL is a possible value. L. NOCOUNT


SET N C U T ON OON SET N C U T O F OON F --suppress 'rows affected' msg

M. Don't use "= NULL". Use "IS NULL" because ANSI NULLs fail all comparisons "NULL = NULL" is false Order of Presedence: (),NOT,AND,OR N. the EXECUTE command can be used to build commands from parts
a. Example 1 create p o d s l y a l rc ipatbe @ b varchar(30) tl as EXECUTE (' E E T * F O ' + @ b ) SLC RM tl b. Example 2 SELECT @ m = " r a e d t b s " p o a b e +" O " d t d v c +" = 6 L G O " l g e i e cd c e t a a a e +@ r j b r v N +@ a a e i e O N +@ o d v c SELECT @ m cd EXECUTE (@ m ) cd

www.fincher.org/tips/General/SQL.shtml

35/38

9/3/12

SQL Examples

O. Terms:
A batch is a set of one or more SQL statements submitted together and executed as a single group. A script is a series of one or more batches submitted one after the other. A script is a file, with a default extension of .SQL Comparison operators (=,<>,>,<,>=,<=), BETWEEN, IN, LIKE, IS NULL, and IS NOT NULL

P. The System supplied databases.


Database Function Master: Model: Msdb: Tempdb: pubs: Controls all user databases and SQL Server as a whole Serves as a template when creating new user databases Provides support for the SQL Executive service Used for temporary working storage for all connections A sample database

Q. Wait, pause, sleep command


W I F R D L Y ' 0 0 : 9 -- sleeps for 59 seconds ATO EA 0:05'

SELECT @ m = " r a e d t b s " p o a b e +" O " cd c e t a a a e +@ r j b r v N + @aaeie d t d v c +" = 6 L G O " l g e i e = 6 O N +@ o d v c +" " SELECT @ m cd EXECUTE (@ m ) cd

R. Get all the column names in a table


SELECT n m FROM s s o u n WHERE i in (SELECT i FROM s s b e t ae yclms d d yojcs where n m = ' y o u n ) ae mclm'

S. Easy way is to access meta data is the 'information_schema' view:


SELECT * FROM i f r a i n s h m .columns nomto_cea

T. How to restore a database FROM a .BAK file


RSOEFLLSOL ETR IEITNY FROM D S = IK ':PormFlsMcootSLSre\SQ$U18BCU\Depnet.a' C\rga ie\irsf Q evrMSLAS5\AKPSRsodnsbk

The above command will show two rows. The database name and the log file name are in the first column, 'LogicalName'. These should be inserted below for 'SDRespondents_Data' and 'SDRespondents_log' respectively. R S O E DATABASE S R s o d n s ETR Depnet FROM D S = IK ':PormFlsMcootSLSre\SQ$U18BCU\Depnet.a' C\rga ie\irsf Q evrMSLAS5\AKPSRsodnsbk WITH M V ' D e p n e t _ a a TO OE SRsodnsDt' ':PormFlsMcootSLSre\SQ$U18Dt\Depnet.d' C\rga ie\irsf Q evrMSLAS5\aaSRsodnsmf, M V ' D e p n e t _ o ' TO OE SRsodnslg ':PormFlsMcootSLSre\SQ$U18Dt\Depnet.d' C\rga ie\irsf Q evrMSLAS5\aaSRsodnslf GO

U. How to see all active requests


SELECT s a t t m , [text], status, t t l e a s d t m , tr_ie oa_lpe_ie D _ a e a a a e i ), b o k n _ e s o _ d w i _ y e B N m (d t b s _ d l c i g s s i n i , a t t p , wi_ie cutm, cmad attm, p_ie omn, lgclras tx_ie rwcut ssini oia_ed, etsz, o_on, eso_d FROM s s m e e _ e u s s AS R y .d _ x c r q e t CROSS A P Y s s m e e _ q _ e t l n h n l ) AS S P L y .d _ x c s l t x (p a _ a d e WHERE s s i n i <> @ S I ; eso_d @PD

www.fincher.org/tips/General/SQL.shtml

36/38

9/3/12

SQL Examples
V. How to retrieve data as xml
Use "FOR XML AUTO" or "FOR XML EXPLICIT" SELECT * FROM s g o p FOR X L A T drus M UO

W. How to select fields that are only letters and numbers?


Since SQL doesn't have a isAlphaOrNumber() function you can use this user function from our friends at simple-talk.com IF O J C _ D ' s l u ' IS NOT NULL B E T I (N I A n m ) DROP FUNCTION I A n m slu GO CREATE FUNCTION d o s l u ] (@ t i g VARCHAR(M X b .[I A n m s r n A )) /* Select dbo.isalnum('how many times must I tell you') Select dbo.isalnum('345rtp') Select dbo.isalnum('co10?') */ R T R S INT EUN AS BEGIN RETURN CASE WHEN P T N E (' [ a z - 0 9 % , @ t i g > 0 T E 0 AIDX %^-AZ-]' srn) HN ELSE 1 END END GO create table t s (D s r p i n varchar(255)) et ecito insert into t s (D s r p i n VALUES (' m k ) et ecito) io' insert into t s (D s r p i n VALUES (' m k ' et ecito) io2) insert into t s (D s r p i n VALUES (' ' m o o ' et ecito) i'Nt k) select * from t s where d o s l u (D s r p i n = 1 /* selects only rows containing only letters and numbers */ et b .I A n m e c i t o )

X. How to validate a sql statement before executing it?


One option is to user FMTONLY, but it's rumored to cause false negatives. SET F T N Y ON MOL -- lets test the next statement select * from t s 2 et SET F T N Y O F MOL F M g 208, L v l 16, S a e 1, L n 5 s ee tt ie Ivldojc nm 'et' nai bet ae ts2. You can also use "SET PARSEONLY ON" and "SET PARSEONLY OFF" , but this just checks syntax, not if a tablename is misspelled.

Y. Connection Strings
Bad example where password is embedded (but occassionally useful for testing on dev boxes) A p i a i n N m =m A p i a i n Data S u c =m D t b s S r e ; u e i =s ;p s w r =m p s w r plcto ae yplcto; ore yaaaeevr sr d a asod yasod

Real solution where password is not in connection string Data S u c =m D t b s S r e ; T u t d C n e t o =y s database=m D t b s N m ore yaaaeevr rse_oncin e; yaaaeae

Z. Working with Devices


Devices are containers for databases and their logs. a. Creating Devices DS II cetsdvcs IK NT rae eie: To create data d v c s y u m s b in m s e . eie o ut e atr D S I I n m =' I R R _ E 1 , IK NT ae LBAYDV' pynm = ':MSLDT\IRR.A' hsae c\SQ\AALBAYDT, v e n = 100, -- must be unique, use sp_helpdevice() dvo -- to find currently used device_number(s) s z = 10240 -- in 2K block s ie DS II IK NT n m =' I R O _ E 2 , ae LBLGDV' pynm = ':MSLDT\IRO.A' hsae c\SQ\AALBLGDT, v e n = 101, dvo

www.fincher.org/tips/General/SQL.shtml

37/38

9/3/12
s z = 4096 ie

SQL Examples
b. Resizing Devices -- you can only increase the size of a device, never shrink DISK RESIZE name='MASTER', SIZE=15360 -- size is in 2k pages c. Deleting Devices Note: When using EntepriseManager to drop a device, it does not drop the .DAT file, instead use: sp_dropdevice logical_name [, DELFILE] -- deletes .DAT file too

AA. Resetting a user's password


s_asod'ysrae, 'ysr' ppswr muenm' m+to

32. THE END


"A SQL query walks into a bar. He approaches two tables and says, Mind if I join you?"

www.fincher.org/tips/General/SQL.shtml

38/38