Tải bản đầy đủ (.pdf) (793 trang)

Wrox SQL functions programmers reference apr 2005 ISBN 0764569015 pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.35 MB, 793 trang )



SQL Functions Programmer’s Reference



SQL Functions Programmer’s Reference
Arie Jones
Ryan K. Stephens
Ronald R. Plew
Robert F. Garrett
Alex Kriegel


SQL Functions Programmer’s Reference
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com
Copyright © 2005 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN 13 978-0-7645-6901-2
ISBN 10 0-7645-6901-5
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
1B/RU/QU/QV/IN
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United
States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600.
Requests to the Publisher for permission should be addressed to the Legal Department, Wiley Publishing, Inc., 10475 Crosspoint


Blvd., Indianapolis, IN 46256, (317) 572-3447, fax (317) 572-4355, or online at />LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS
OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND
SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE
ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD
WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR
OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A
CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE
PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY
HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services or to obtain technical support, please contact our Customer Care
Department within the U.S. at (800) 762-2974, outside the U.S. at (317) 572-3993 or fax (317) 572-4002.
For technical support, please visit www.wiley.com/techsupport.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not be available in electronic books.
Library of Congress Cataloging-in-Publication Data:
SQL functions programmer’s reference / Arie Jones ... [et al.].
p. cm.
Includes bibliographical references and index.
ISBN 0-7645-6901-5 (paper/website : alk. paper)
1. SQL (Computer program language) I. Jones, Arie.
QA76.73.S67S674 2005
005.13’3--dc22
2005002765
Trademarks: Wiley, the Wiley Publishing logo, Wrox, the Wrox logo, Programmer to Programmer, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may
not be used without written permission. All other trademarks are the property of their respective owners. Wiley Publishing, Inc., is
not associated with any product or vendor mentioned in this book.


About the Authors
Arie Jones
Arie Jones is a senior database administrator for Perpetual Technologies, Inc. (www.perptech.com). He holds

a master’s degree in physics from Indiana State University and also works as the chief Web architect/DBA
for the USPFO for Indiana. Arie’s main specialty is in developing .NET-based database solutions for the government. He and his wife and family live outside of Indianapolis, Indiana.

Ryan K. Stephens
Ryan Stephens is the president and CEO of Perpetual Technologies, Inc. (www.perptech.com), an Indianapolisbased IT firm specializing in database technologies. Ryan has been working with SQL and databases for 15
years and has held the positions of project manager, database administrator, and programmer/analyst. Ryan
has been teaching database courses for local universities since 1997 and has authored several internationally
published books on topics such as database design, SQL, database architecture, database administration, and
Oracle. Ryan enjoys discovering new ways to optimize the use of technology to streamline business operations,
as well as empowering others to do the same. Ryan and his wife live in Indianapolis with their three children.

Ronald R. Plew
Ronald R. Plew is vice president and CIO for Perpetual Technologies, Inc. (www.perptech.com) in
Indianapolis, Indiana. Ron is a Certified Oracle Professional. He has coauthored several internationally
published books on SQL and database technology. Ron is also an adjunct professor for Vincennes
University in Indiana, where he teaches SQL and various database courses. Ron holds a bachelor of
science degree in business administration/management from Indiana Institute of Technology out of Fort
Wayne, Indiana. Ron recently retired from the Indiana Army National Guard, where he served as a
programmer/analyst. His hobbies include automobile racing, chess, golf, and collecting Indy 500
memorabilia. Ron resides in Indianapolis with his wife Linda.

Robert F. Garrett
Bob Garrett is the software development manager at Perpetual Technologies, Inc. (www.perptech.com).
Bob’s languages of preference are Java, C++, and English. He has extensive experience integrating applications with relational databases. Bob has a degree in computer science and mathematics from Purdue
University, and lives with his wife and daughter near Indianapolis.

Alex Kriegel
Alex Kriegel is a professional database systems analyst with a major manufacturing firm in Oregon. He
has more than 10 years of database experience working with Microsoft SQL Server, Oracle, DB2, Sybase,
and PostgreSQL both as developer and DBA. Alex has a bachelor of science degree in solid-state physics

from State Polytechnic Institute of Minsk, Belarus, and has earned the Microsoft Certified Solution
Developer (MCSD) accreditation. He is the author of SQL Bible. Alex wrote the first draft of approximately two-thirds of this book.


Contributing Authors
Joshua Stephens
Joshua Stephens is a systems administrator/DBA for Perpetual Technologies, Inc. (www.perptech.com).
He has eight years of experience in various IT areas. As a former technical writer and trainer, he continues to enjoy helping others through writing. He holds a bachelor of arts degree in pure mathematics and
physics from Franklin College. He lives in Franklin, Indiana, with his wife and daughter.

Richard Bulley
Richard is a Ferris State University graduate and received a master of arts degree from Ball State
University. He has had 20 years of data processing experience with the United States Air Force and is a
United States Air Force Reserves Retiree and currently has over six years of experience as a Sybase and
MS SQL Server system DBA.


Credits
Acquisitions Editor

Vice President & Executive Group Publisher

Jim Minatel

Richard Swadley

Development Editor

Vice President and Publisher


Kevin Shafer

Joseph B. Wikert

Production Editor

Project Coordinator

Gabrielle Nabi

Ryan Steffen

Technical Editor

Graphics and Production Specialists

Wiley-Dreamtech India Pvt Ltd

April Farling, Carrie Foster, Denny Hager,
Julie Trippetti

Copy Editor
Publication Services, Inc.

Quality Control Technicians

Editorial Manager

Joe Niesen
John Greenough


Mary Beth Wakefield

Proofreading and Indexing
TECHBOOKS Production Services


I would like to dedicate this book to my wife, Jacqueline, for being understanding and supportive during
the long hours that it took to complete this book.
— Arie Jones
For Tina, Daniel, Autumn, and Alivia. You are my inspiration.
— Ryan Stephens
For Linda
— Ron Plew
For Becky and Libby
— Bob Garrett


Acknowledgments
Shortly after we accepted this project, it became clear how much of a team effort would be needed to
make this book a must-have for anyone’s SQL library. Fortunately, I have an incredible technical team
that knows how to come together and get the job done. Most of my thanks go to Arie Jones. Arie stepped
up when I needed the most help, unafraid of commitment, confidently accepting another aggressive
assignment. Our author team included Arie Jones, Ron Plew, Bob Garrett, Alex Kriegel, and myself.
Contributing authors were Joshua Stephens and Richard Bulley. I cannot say enough about their professionalism and technical proficiency. Thank you for being part of another successful project!
Probably as no surprise to the Wiley audience, the author team thanks the editorial staff at Wiley, which
is one of the best with whom we have had the pleasure of working. Specifically, we appreciate Jim
Minatel’s efforts and confidence in our team, Kevin Shafer’s strict attention to detail, and the technical
editorial team’s thoroughness. Their dedication, patience, and thoroughness, we believe, reflect directly
on the quality and timely delivery of this book, which would not have been possible without each of

them, as well as the unmentioned Wiley staff behind the scenes.
— Ryan Stephens and the author team



Contents
Acknowledgments
Introduction
Chapter 1: Exploring Popular SQL Implementations
Introduction to SQL
Understanding the SQL Standard
Overview of Vendor Implementations of SQL
Oracle
IBM DB2 UDB
Microsoft SQL Server and Sybase
MySQL
PostgreSQL

Connecting to SQL Databases
ANSI SQL Data Types
Creating SQL Databases
Querying SQL Databases
Manipulating Data in SQL Databases
Summary

Chapter 2: Functions: Concept and Architecture
What Is a Function?
Simple UNIX Shell Function Example
Simple SQL Function Example


ANSI SQL Functions
Built-in Functions
Executing Built-in Functions
Practical Uses of Functions

Creating, Compiling, and Executing a SQL Function
Passing Parameters by Value or by Reference
Scope of a Function
Better Security
Overloading

Classifying SQL Functions: Deterministic and Non-Deterministic Functions
Oracle
IBM DB2 UDB

ix
xxxv

1
1
2
2
3
3
3
3
4

4
5

5
7
9
11

13
13
14
15

15
16
17
17

18
22
24
25
25

27
29
29


Contents
Microsoft SQL Server
Sybase
MySQL and PostgreSQL


Summary

Chapter 3: Comparison of Built-in SQL Functions by Vendor
Types of Functions
Classifying Built-in SQL Functions
Oracle
IBM DB2 UDB
Microsoft SQL Server and Sybase ASE
MySQL
PostgreSQL

Overview of Built-in Functions by Vendor
Summary

Chapter 4: SQL Procedural Extensions and User-Defined Functions
Procedural versus Declarative Languages
ANSI SQL Guidance for Procedural Extensions to SQL
SQL Procedural Extensions by Vendor
Oracle PL/SQL
Microsoft or Sybase Transact-SQL
IBM Procedural SQL
MySQL
PostgreSQL

Summary

Chapter 5: Common ANSI SQL Functions
ANSI Query Syntax
Aggregate Functions


32

33
33
34
35
36
37
39
39

40
48

49
49
51
52
52
54
55
57
57

58

59
60
60


AVG()
COUNT()
MAX() and MIN()
SUM()

62
63
64
65

String Functions

65

ASCII()
CHR() or CHAR()
CONCAT()
LOWER() and UPPER()
LENGTH() or LEN()
REPLACE()

xii

30
31
31

66
67

67
68
68
69


Contents
Mathematical Functions
ABS()
ACOS()
ASIN()
ATAN() and ATAN2()
CEIL() or CEILING() and FLOOR()
COS()
COSH()
COT()
DEGREES() and RADIANS()
EXP()
LOG(), LN(), LOG2(), and LOG10()
MOD()
PI()
POWER()
RAND()
ROUND()
SIGN()
SINH()
SQUARE()
SQRT()
TAN()
TANH()

TRUNC() or TRUNCATE()

Miscellaneous Functions
COALESCE()
NULLIF()

Summary

Chapter 6: Oracle SQL Functions
Oracle Query Syntax
Aggregate Functions

69
72
73
73
74
74
75
75
75
76
76
77
77
79
79
80
80
81

82
82
83
83
83
84

85
85
85

86

87
87
90

AVG()
CORR()
COUNT()
GROUPING()
MAX() and MIN()
STDDEV()
SUM()

91
92
93
94
95

95
96

Analytic Functions

97

xiii


Contents
Character Functions
CHR() and NCHR()
INITCAP()
LPAD() and RPAD()
TRIM(), LTRIM(), and RTRIM()
REPLACE()
SOUNDEX()
SUBSTR()
TRANSLATE()

97
99
100
101
102
103
103
104
105


Regular Expressions
Conversion Functions

106
106

CAST()
COMPOSE()
CONVERT()
DECOMPOSE()
TO_CHAR()
TRANSLATE...USING
UNISTR()

107
108
108
110
110
113
113

Date and Time Functions
ADD_MONTHS()
DBTIMEZONE and SESSIONTIMEZONE
EXTRACT()
MONTH_BETWEEN()
NEW_TIME()
ROUND()

SYSDATE
TRUNC()

114
115
116
117
118
118
119
120
121

Numeric Functions

123

ABS()
BITAND()
CEIL() and FLOOR()
MOD()
SIGN()
ROUND()
TRUNC()

123
124
124
125
125

126
127

Object Reference Functions
Miscellaneous Single-Row Functions
COALESCE()
DECODE()
DUMP()
GREATEST()
NULLIF()
NVL()

xiv

127
127
128
129
130
131
132
133


Contents
NVL2()
UID
VSIZE()

133

134
134

Summary

135

Chapter 7: IBM DB2 Universal Database (UDB) SQL Functions

137

DB2 UDB Query Syntax
String Functions

138
140

CONCAT()
INSERT()
LEFT() and RIGHT()
LENGTH()
LOCATE() and POSSTR()
LTRIM() and RTRIM()
REPEAT()
REPLACE()
SOUNDEX()
SPACE()
SUBSTR()
TRUNC() or TRUNCATE()


142
142
143
143
144
144
145
145
146
146
147
147

Date and Time Functions

148

DATE()
DAY()
DAYNAME()
DAYOFWEEK()
DAYOFWEEK_ISO()
DAYOFYEAR()
DAYS()
HOUR()
JULIAN_DAY()
MICROSECOND()
MIDNIGHT_SECONDS()
MINUTE()
MONTH()

MONTHNAME()
SECOND()
TIME()
TIMESTAMP()
TIMESTAMPDIFF()
TIMESTAMP_FORMAT()
TIMESTAMP_ISO()
WEEK()

150
151
151
152
152
153
153
153
154
155
155
156
156
157
157
157
158
159
160
160
160


xv


Contents
WEEK_ISO()
YEAR()

Conversion Functions
DEC or DECIMAL
HEX()
DOUBLE or DOUBLE_PRECISION
INT() or INTEGER() and SMALLINT()
TRANSLATE()
VARCHAR()

Security Functions
DECRYPT_BIN()
DECRYPT_CHAR()
ENCRYPT()
GETHINT()

IBM DB2 UDB Special Registers
CURRENT DATE
CURRENT DEFAULT TRANSFORM GROUP
CURRENT DEGREE
CURRENT EXPLAIN MODE
CURRENT EXPLAIN SNAPSHOT
CURRENT ISOLATION
CURRENT NODE

CURRENT PATH
CURRENT QUERY OPTIMIZATION
CURRENT REFRESH AGE
CURRENT SCHEMA
CURRENT SERVER
CURRENT TIME
CURRENT TIMESTAMP
CURRENT TIMEZONE
SESSION_USER
USER

161
161

162
163
164
164
165
165
166

167
167
168
168
169

169
170

171
171
171
172
172
173
173
174
174
174
175
175
175
176
176
177

Miscellaneous Functions

177

COALESCE() and VALUE()
DIGITS()
GENERATE_UNIQUE()
NULLIF()
RAND()
TABLE_NAME()
TYPE_ID()
TYPE_NAME()


178
179
179
180
180
181
182
182

Summary

xvi

182


Contents
Chapter 8: Microsoft SQL Server Functions
SQL Server Query Syntax
String Functions
ASCII()
CHAR()
CHARINDEX()
DIFFERENCE()
LEFT() and RIGHT()
LEN()
LOWER()
LTRIM() and RTRIM()
NCHAR()
PATINDEX()

REPLACE()
QUOTENAME()
REPLICATE()
REVERSE()
SOUNDEX()
SPACE()
STR()
STUFF()
SUBSTRING()
UNICODE()
UPPER()

Date and Time Functions
DATEADD()
DATEDIFF()
@@DATEFIRST()
DATENAME()
DATEPART()
DAY()
GETDATE() and GETUTCDATE()
MONTH()
YEAR()

Metadata Functions
COL_LENGTH()
DB_ID()
DB_NAME()
FILE_ID()
FILE_NAME()


183
183
185
187
187
188
188
189
189
190
190
191
191
192
192
192
193
193
194
194
195
196
196
196

197
198
199
199
200

200
201
202
202
203

203
204
205
205
206
207

xvii


Contents
Configuration Functions

207

@@CONNECTION
@@LANGID
@@LANGUAGE
@@LOCK_TIMEOUT
@@MAX_CONNECTIONS
@@NESTLEVEL
@@OPTIONS
@@SPID
@@VERSION


207
208
208
210
210
211
211
211
212

Security Functions

212

HAS_DBACCESS()
SUSER_SID()
SUSER_SNAME()
USER
USER_ID()
USER_NAME()

213
214
214
214
215
215

System Functions


216

APP_NAME()
CASE
CAST() and CONVERT()
COALESCE()
CURRENT_TIMESTAMP
CURRENT_USER
DATALENGTH()
@@ERROR
HOST_ID()
HOST_NAME()
@@IDENTITY
IDENTITY()
ISDATE()
ISNULL()
ISNUMERIC()
NEWID()
PERMISSIONS()
ROWCOUNT_BIG and @@ROWCOUNT
@@TRANCOUNT
COLLATIONPROPERTY()
SCOPE_IDENTITY()

System Statistical Functions
@@CPU_BUSY
@@IDLE

xviii


219
219
220
224
225
225
226
226
227
227
228
228
229
229
230
230
231
231
232
233
233

234
235
235


Contents
@@IO_BUSY

@@TIMETICKS
@@TOTAL_ERRORS
@@TOTAL_READ
@@TOTAL_WRITE
fn_virtualfilestats()

Undocumented Functions
ENCRYPT()
FN_GET_SQL()
@@MICROSOFTVERSION
PWDCOMPARE()
PWDENCRYPT()
TSEQUAL()

Summary

Chapter 9: Sybase ASE SQL Built-In Functions
Sybase Query Syntax
String Functions
CHARINDEX()
CHAR_LENGTH()
COMPARE()
DIFFERENCE()
LTRIM() and RTRIM()
PATINDEX()
REPLICATE()
REVERSE()
RIGHT() and LEFT()
SORTKEY()
SOUNDEX()

SPACE()
STR()
STUFF()
SUBSTRING()
USCALAR()

Date and Time Functions
DATEADD()
DATEDIFF()
DATENAME()
DATEPART()
GETDATE()

236
236
236
237
237
238

239
240
240
241
241
242
242

243


245
246
247
249
250
250
252
252
253
254
254
255
255
257
257
257
258
259
259

260
261
262
262
263
264

xix



Contents
Conversion Functions
CONVERT()
INTTOHEX()
HEXTOINT()

Security Functions
IS_SEC_SERVICE_ON()
SHOW_SEC_SERVICES()

Aggregate Functions
AVG()
COUNT()
MAX()
MIN()
SUM()

Mathematical Functions
ABS()
ACOS()
ASIN()
ATAN()
ATN2()
CEILING()
COS()
COT()
DEGREES()
EXP()
FLOOR()
LOG()

LOG10()
PI()
POWER()
RADIANS()
RAND()
ROUND()
SIGN()
SIN()
SQRT()
TAN()

Text and Image Functions
TEXTPTR()
TEXTVALID()

xx

264
266
270
271

271
272
272

272
273
274
274

275
275

275
277
278
278
278
279
279
280
280
280
281
281
281
282
282
282
283
283
284
285
285
286
286

286
287
287


System Functions

288

COL_LENGTH()
COL_NAME()

289
290


Contents
DATALENGTH()
DB_ID()
DB_NAME()
OBJECT_ID()
OBJECT_NAME()
RAND()
SUSER_ID()
SUSER_NAME()
TSEQUAL()
USER()
USER_ID()
USER_NAME()
VALID_NAME()
VALID_USER()

Unary System Functions
@@BOOTTIME

@@CLIENT_CSID
@@CLIENT_CSNAME
@@CONNECTIONS
@@CPU_BUSY
@@ERROR
@@ERRORLOG
@@IDENTITY
@@IDLE
@@IO_BUSY
@@LANGID
@@LANGUAGE
@@MAXCHARLEN
@@MAX_CONNECTIONS
@@NCHARSIZE
@@NESTLEVEL
@@OPTIONS
@@PROBESUID
@@ROWCOUNT
@@SPID
@@SQLSTATUS
@@TIMETICKS
@@TOTAL_ERRORS
@@TOTAL_READ
@@TOTAL_WRITE
@@TRANCHAINED
@@TRANCOUNT

291
291
292

292
293
293
294
295
295
296
296
297
297
298

299
301
301
302
302
303
303
303
304
305
305
305
306
306
306
307
307
308

308
308
309
309
310
310
311
311
311
312

xxi


Contents
@@TRANSTATE
@@UNICHARSIZE
@@VERSION
@@VERSION_AS_INTEGER

Summary

Chapter 10: MySQL Functions
MySQL Query Syntax
Aggregate Functions

312
313
313
314


314

315
315
317

AVG()
COUNT()
MAX() and MIN()
SUM()

318
318
319
319

Numeric Functions

319

ABS()
ACOS()
ASIN()
ATAN()
ATAN2()
BIT_AND()
BIT_COUNT()
BIT_OR()
CEIL() or CEILING()

CONV()
COS()
COT()
DEGREES()
EXP()
FLOOR()
FORMAT()
GREATEST()
INTERVAL()
LEAST()
LOG()
LOG10()
MOD()
OCT()
PI()
POW() or POWER()
RADIANS()
RAND()

322
323
323
323
323
324
324
325
325
325
326

326
326
327
327
327
328
328
328
329
329
329
330
330
330
331
331

xxii


Contents
ROUND()
SIGN()
SIN()
SQRT()
STD() or STDDEV()
TAN()
TRUNCATE()

String Functions

ASCII()
BIN()
CHAR()
COMPRESS()
CONCAT()
CONCAT_WS()
ELT()
FIELD()
FIND_IN_SET()
HEX()
INSERT()
INSTR()
ISNULL()
LCASE() or LOWER()
LEFT()
LENGTH(), CHAR_LENGTH(), and CHARACTER_LENGTH()
LOCATE()
LPAD()
LTRIM()
MAKE_SET()
NULLIF()
OCT()
ORD()
REPEAT()
REPLACE()
REVERSE()
RIGHT()
RPAD()
RTRIM()
SOUNDEX()

SUBSTRING()
SUBSTRING_INDEX()
TRIM()
UCASE() or UPPER()

331
332
332
332
332
333
333

333
338
339
339
339
340
340
341
341
342
342
342
343
343
344
344
344

345
346
346
346
347
347
348
348
348
349
349
349
350
350
350
351
352
352

xxiii


×