Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
BIS 512 - DBMSAdvanced SQL – SPs, Cursors, Built-in Functions
Ahmet Onur Durahimhttp://www.mis.boun.edu.tr/durahim/
Learning Objectives
• Stored Procedures
• Cursors
• Built-in Functions
Stored Procedures• Stored Procedures (SPs) enables application logic
to be stored and executed at the database server
• Execute application code at the DB server– Instead of retrieving data and executing the application
logic in a separate process (program)
• Advantages– Can capsulate application logic while staying “close”
to the data• Need to bring computation to the data
– Should not bring data to computation due to network and other costs (i.e., bandwidth, time)
– Reuse of application logic by different users
– Avoid tuple-at-a-time return of records through cursors
Benefits of Using Stored Procedures• Stored procedure reduces the amount of information sent to
the database server– become a more important benefit when the bandwidth of the
network is less– If we send the SQL query which is executing in a loop to the server
through network and the network gets disconnected• then the execution of the SQL statement doesn't return the expected
results
• Compilation step is required only once when the SP is created– does not require recompilation before executing unless it is
modified and reutilizes the same execution plan– whereas the SQL statements need to be compiled every time
whenever it is sent for execution • even if we send the same SQL statement every time
Benefits of Using Stored Procedures• It helps in re-usability of the SQL code
– because it can be used by multiple users and by multiple clients • since we need to just call the SP instead of writing the same SQL
statement every time
– helps in reducing the development time
• It is helpful in enhancing the security– since we can grant permission to the user for executing the SP
instead of giving permission on the tables used in the SP
• It is useful to use the database for storing the business logicin the form of SP – it makes it secure
• can be encrypted and does not leave the organization
– if any change is needed in the business logic, then we may only need to make changes in the SP and not in the files contained on the web server
Stored Procedure Syntax--SQL Server Stored Procedure Syntax CREATE { PROC | PROCEDURE } [schema_name.] procedure_name [; number]
[ { @parameter [ type_schema_name. ] data_type } [ VARYING ] [ = default ] [ OUT | OUTPUT | [READONLY]
] [ ,...n ] [ WITH <procedure_option> [ ,...n ] ] [ FOR REPLICATION ] AS { [ BEGIN ] sql_statement [;] [ ...n ]
[ END ] } [;]
<procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] [ EXECUTE AS Clause ]
Stored Procedure Syntax--SQL Server Stored Procedure Syntax CREATE { PROC | PROCEDURE } [schema_name.] procedure_name [; number]
[ { @parameter [ type_schema_name. ] data_type } [ VARYING ] [ = default ] [ OUT | OUTPUT | [READONLY]
] [ ,...n ] [ WITH <procedure_option> [ ,...n ] ] [ FOR REPLICATION ] AS { [ BEGIN ] sql_statement [;] [ ...n ]
[ END ] } [;]
<procedure_option> ::= [ ENCRYPTION ] [ RECOMPILE ] [ EXECUTE AS Clause ]
Simple Stored ProceduresCREATE PROCEDURE ShowNumbersOfOrders
SELECT C.cid, C.cname, COUNT(*)FROM Customers C, Orders OWHERE C.cid = O.cidGROUP BY C.cid, C.cname
• SPs can also have parameters– Have to be valid SQL types– Have one of the three different modes
• IN parameters are arguments to the SP• OUT parameters are returned from the SP• INOUT parameters combine the properties of IN and OUT
– Contain values to be passed to the SPs, and the SP can set their values as return values
– SPs enforce strict type conformance• If a parameter is of type INTEGER, it cannot be called with an argument of type VARCHAR
CREATE PROCEDURE AddInventory (
IN book_isbn CHAR(10),IN addedQty INTEGER )
UPDATE BooksSET qty_in_stock = qty_in_stock + addedQtyWHERE book_isbn = isbn
Search by ISBN SP
CREATE PROCEDURE SearchByISBN (IN book_isbn CHAR(10))
SELECT B.title, B.author, B.qty_in_stock,
B.price, B.year_published
FROM Books B
WHERE B.isbn = book_isbn
Simple Stored ProceduresCREATE PROCEDURE RateCustomer (
IN custid INTEGER,IN year INTEGER )
DECLARE rating INTEGERDECLARE numOrders INTEGER
SET numOrders = (SELECT COUNT(*) FROM Orders O
WHERE O.tid = custId);
IF (numOrders>10)
THEN rating=2;
ELSE IF (numOrders>5)
THEN rating=1;
ELSE rating=0;
END IF;
RETURN rating
Return Rating of the Sailor SP(SQL-Server Version)
CREATE PROCEDURE RatingOfSailor
@sailorId INT, @year INT, @rating INT
AS
BEGIN
DECLARE @numReservations INTEGER
SET @numReservations = (SELECT COUNT(*) FROM Reserves R
WHERE R.SID = @sailorId);
IF (@numReservations > 3)
SET @rating = 2
ELSE IF (@numReservations > 1)
SET @rating = 1
ELSE
SET @rating = 0
RETURN @rating
END
Stored Procedures
• We can declare local variables using the DECLAREstatement– we declare two local variables: 'rating' and 'numOrders'
• PSM/SQL functions return values via the RETURNstatement– we return the value of the local variable 'rating'
• We can assign values to variables with the SETstatement– we assigned the return value of a query to the variable
'numOrders‘
• SQL/PSM has branches and loops
Stored Procedures• Stored procedures may return result sets
– i.e., the results of a SELECT statement– Returned result sets can be processed using cursors, by other
stored procedures, by associating a result set locator, or by applications
• Stored procedures may contain declared variables for processing data and cursors that allow it to loop through multiple rows in a table
• Stored procedure flow control statements typically include IF, WHILE, LOOP, REPEAT, and CASE statements, etc.
• Stored procedures can receive variables, return results or modify variables and return them– depending on how and where the variable is declared
• The exact and correct implementation of stored procedures varies from one database system to the another
SQL/PSM (Persistent Stored Modules)• SQL/PSM is an ISO standard mainly defining an extension
of SQL with a procedural language for use in stored procedures
• SQL statements for defining, managing, and invoking routines were actually incorporated into part 2 SQL/Foundation, leaving only the procedural language (imperative programming) itself as SQL/PSM– SQL is a declarative language in which the expected result or
operation is given without the specific details about how to accomplish the task• The steps required to execute SQL statements are handled
transparently by the SQL database
– SQL is non-procedural because procedural languages generally require the details of the operations to be specified• opening and closing tables, loading and searching indexes, or flushing
buffers and writing data to file systems
SQL/PSM (Persistent Stored Modules)• SQL/PSM standardizes syntax and semantics for control flow,
exception handling (called "condition handling" in SQL/PSM), local variables, assignment of expressions to variables and parameters, and (procedural) use of cursors
• SQL/PSM also defines an information schema (metadata) for stored procedures– SQL/PSM is one language in which methods for the SQL:1999
structured types can be defined
• Implementations of similar languages– Open Source
• MySQL stored procedures: a procedural lang. that closely adheres to SQL/PSM
• PL/pgSQL: PostgreSQL language similar to SQL/PSM and PL/SQL
– Proprietary• PL/SQL: Oracle proprietary language for stored procedures• Transact-SQL (T-SQL): Microsoft and Sybase equivalent
SPs – SQL Server’s T-SQL
• Transact-SQL (T-SQL) is Microsoft's and Sybase's proprietary extension to SQL– SQL (Structured Query Language) is a standardized
computer language that was originally developed by IBM for querying, altering and defining relational databases, using declarative statements
– T-SQL expands on the SQL standard to include procedural programming, local variables, various support functions for string processing, date processing, mathematics, etc. and changes to the DELETE and UPDATE statements• These additional features make Transact-SQL
SPs – Variables• Transact-SQL provides the following statements
to declare and set local variables– DECLARE, SET and SELECT
Declare a variableDECLARE @var1 NVARCHAR(30)
DECLARE @varAge INT
DECLARE @revenue FLOAT
Assign a value into a declared variableSET @var1 = ‘Himmet‘
SET @varAge = 22
Assign a value into a variable in SQL StatementSELECT @var1 = Name
FROM Store WHERE CustomerID = 9999
SELECT @revenue = Sales.Revenue
FROM Sales WHERE CustomerID = 9999
SPs – Flow Control• Keywords for flow control in Transact-SQL include
– BEGIN and END, BREAK, CONTINUE, GOTO, IF and ELSE, RETURN, WAITFOR, and WHILE
• IF and ELSE allow conditional execution
• Statement will print – “It is the weekend” if the current date is a weekend day – “It is a weekday” if the current date is a weekday– This code assumes that Sunday is configured as the first
day of the week in the @@DATEFIRST setting
IF DATEPART(dw, GETDATE())=7 OR DATEPART(dw, GETDATE())=1
PRINT 'It is the weekend.'
ELSE
PRINT 'It is a weekday.'
@@ denotes Global Variables reserved by SQLServer
SPs – Flow Control
• BEGIN and END mark a block of statements
– If more than one statement is to be controlled by the conditional
IF DATEPART(dw, GETDATE())=7 OR DATEPART(dw, GETDATE())=1
BEGIN
PRINT 'It is the weekend.'
PRINT 'Get some rest on the weekend!'
END
ELSE
BEGIN
PRINT 'It is a weekday.'
PRINT 'Get to work on a weekday!'
END
SPs – Flow Control• WAITFOR will wait for a given amount of time, or until a
particular time of day – Can be used for delays or to block execution until the set time
• RETURN is used to immediately return from a stored procedure or function
DECLARE @i INT
SET @i = 0
WHILE @i < 5
BEGIN
IF @i > 2
BEGIN
PRINT 'Hey stop there'
BREAK
END
PRINT 'Hello world.'
PRINT @i
SET @i = @i + 1
END
• BREAK ends the enclosing WHILE loop, while CONTINUEcauses the next iteration of the loop to execute
SPs – Bulk Insert
• BULK INSERT is a Transact-SQL statement that implements a bulk data-loading process, inserting multiple rows into a table, reading data from an external sequential file– Use of BULK INSERT results in better performance than processes
that issue individual INSERT statements for each row to be added
BULK INSERT AdventureWorks2012.Sales.SalesOrderDetail
FROM 'f:\orders\lineitem.tbl'
WITH
(
FIELDTERMINATOR =' |',
ROWTERMINATOR =' |\n'
);
Try Catch
-- begin transaction
BEGIN TRAN
BEGIN TRY
-- execute each statement
INSERT INTO MYTABLE(NAME) VALUES ('ABC')
INSERT INTO MYTABLE(NAME) VALUES ('123')
-- commit the transaction
COMMIT TRAN
END TRY
BEGIN CATCH
-- rollback the transaction because of error
ROLLBACK TRAN
END CATCH
• Beginning with SQL Server 2005, Microsoft introduced additional TRY CATCH logic to support exception (handling) type behaviour– This behaviour enables developers to simplify their code and leave out
@@ERROR checking after each SQL execution statement
Creating SPs in SQL Server
USE AdventureWorks2012;
GO
CREATE PROCEDURE uspGetEmployeesTest2
@LastName nvarchar(50),
@FirstName nvarchar(50)
AS
SELECT FirstName, LastName, Department
FROM vEmployeeDepartmentHistory
WHERE FirstName = @FirstName AND LastName = @LastName
AND EndDate IS NULL;
GO
http://msdn.microsoft.com/en-us/library/ms345415.aspx
Executing SPs in SQL Server
EXECUTE uspGetEmployeesTest2 N'Ackerman', N'Pilar';
-- Or
EXEC uspGetEmployeesTest2 @LastName = N'Ackerman',
@FirstName = N'Pilar';
GO
-- Or
EXECUTE uspGetEmployeesTest2 @FirstName = N'Pilar',
@LastName = N'Ackerman';
GO
Return data from SPs• Three common ways to return data from stored procedures
– returning result sets (SELECT statements)– using output variables– using the RETURN statement
• using Result Sets– Result sets are what you get when you run a simple SELECT statement
inside a stored procedure– Let's suppose you want a stored procedure to return a list of all the people
with a given last name
CREATE PROCEDURE dbo.sp_GetPeopleByLastName (@LastName NVARCHAR(50))
ASSELECT BusinessEntityID, FirstName, LastNameFROM Person.PersonWHERE LastName = @LastNameORDER BY BusinessEntityID
EXEC dbo.sp_GetPeopleByLastName @LastName='Alexander'
Storing the Result Set
DECLARE @People TABLE (
BusinessEntityID INT,
FirstName NVARCHAR(50),
LastName NVARCHAR(50))
INSERT @People (BusinessEntityID, FirstName, LastName)
EXEC dbo.sp_GetPeopleByLastName @LastName = 'Alexander'
SELECT COUNT(*) FROM @People
SELECT TOP 10 * FROM @People
GO
• If we want to capture a result set using T-SQL we'll need a place to store it– Temporary Tables work well for that
Return data from SPs• using OUTPUT variables
– If we just want to return a single value (or a couple of values) we can use output variables
CREATE PROCEDURE sp_GetCountByLastName (@LastName NVARCHAR(50),@LastNameCount INT OUTPUT )
ASSELECT @LastNameCount = COUNT(*)FROM PersonWHERE LastName = @LastName
– If we want to return the value using T-SQL
DECLARE @TheCount INT
EXEC sp_GetCountByLastName@LastName = 'Alexander',@LastNameCount = @TheCount OUTPUT
SELECT TheCount = @TheCountGO
Return data from SPs• using RETURN statement
– It only returns a single numeric value (the most limiting)– Most commonly used to return a status result or error code from a
procedure
CREATE PROCEDURE sp_RatingOfSailor
(@sailorId INT, @year INT, @rating INT)AS
DECLARE @numReservations INTEGERSET @numReservations = (SELECT COUNT(*) FROM Reserves R
WHERE R.SID = @sailorId);IF (@numReservations > 3)SET @rating = 2
ELSE IF (@numReservations > 1)SET @rating = 1
ELSESET @rating = 0
RETURN @rating
– Executing a RETURN statement causes a SP to stop executing and return control back to the calling program• often used to test for error conditions and stop processing if one is found
Fetching returned value from SP
DECLARE @rating INTEXEC @rating = sp_RatingOfSailor
@sailorId=22,@year=2011,@rating=-1
SELECT 'Return Value' = @rating
Debugging SPs in SQL Server• The Transact-SQL debugger allows you to interactively
debug SPs by displaying the – SQL call stack– local variables– parameters for the SQL stored procedure
• As with debugging in other programming languages, you can – view and modify local variables and parameters– view global variables– control and manage breakpoints while debugging your
Transact-SQL script
Create Stored Procedure
Create Stored Procedure
Cursors• Impedance Mismatch problem
– occurs because SQL operates on sets of records, whereas programming languages like C do not cleanly support a set-of-records abstraction
• Cursor is a control structure that enables traversal over the records in a database
– used to process individual rows (one at a time) returned by database system queries (from a relation)
• Can declare a cursor on a relation or query statement (which generates a relation)
Cursors• Once a Cursor is declared
– Open a cursor: positions the cursor just before the first row– Repeatedly Fetch a tuple, then move the cursor until all
tuples have been retrieved • move cursor to the next row, to the row after the next n, to the first
row, or to the previous row, etc. – by specifying parameters for the FETCH command
– Close the cursor– Can use a special clause, called ORDER BY, in queries that are
accessed through a cursor, to control the order in which tuples are returned• Fields in ORDER BY clause must also appear in SELECT clause
– The ORDER BY clause, which orders answer tuples, is onlyallowed in the context of a cursor
• Can also modify/delete tuple pointed to by a cursor
Cursor – ISO syntaxISO SyntaxDECLARE cursor_name [ INSENSITIVE ] [ SCROLL ] CURSOR
[ WITH HOLD ]FOR select_statement
[ ORDER BY order-item-list ][ FOR { READ ONLY | UPDATE [ OF column_name [ ,...n ] ] } ]
[;]
Transact-SQL Extended Syntax DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ]
[ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING ]
FOR select_statement
[ FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]
Cursor that gets names of sailors who’ve reserved a red boat, in alphabetical order
• It is illegal to replace S.sname by, say, S.sid in the ORDER BY clause! (Why?)
• Can we add S.sid to the SELECT clause and replace S.sname by S.sid in the ORDER BY clause?
• This does not apply to T-SQL (in SQL-Server)
EXEC SQL DECLARE sinfo CURSOR FOR
SELECT S.sname
FROM Sailors S, Boats B, Reserves R
WHERE S.sid=R.sid AND R.bid=B.bid AND B.color=‘red’
ORDER BY S.sname
Cursor ExamplesUSE AdventureWorks2012
GO
DECLARE @ProductID INT
DECLARE @getProductID CURSOR
SET @getProductID = CURSOR FOR
SELECT ProductID FROM Production.Product
OPEN @getProductID
FETCH NEXT FROM @getProductID INTO @ProductID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @ProductID
FETCH NEXT FROM @getProductID INTO @ProductID
END
CLOSE @getProductID
DEALLOCATE @getProductID
GO
Print out ProductID from the Product Table
-- Example cursor where backups are issued in a serial manner
DECLARE @name VARCHAR(50) -- DB name DECLARE @path VARCHAR(256) -- path for backup files DECLARE @fileName VARCHAR(256) -- filename for backup DECLARE @fileDate VARCHAR(20) -- used for file name
SET @path = 'C:\Backup\'SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
DECLARE db_cursor CURSOR FORSELECT name FROM MASTER.dbo.sysdatabasesWHERE name NOT IN ('master','model','msdb','tempdb')
OPEN db_cursorFETCH NEXT FROM db_cursor INTO @name
WHILE @@FETCH_STATUS = 0 BEGIN
SET @fileName = @path + @name + '_' + @fileDate + '.BAK'BACKUP DATABASE @name TO DISK = @fileNameFETCH NEXT FROM db_cursor INTO @name
ENDCLOSE db_cursorDEALLOCATE db_cursor
Cursor Examples - 2
Cursor ExamplesSET NOCOUNT ON;DECLARE @vendor_id int, @vendor_namenvarchar(50), @message varchar(80),@product nvarchar(50);
PRINT '-------- Vendor Products Report --------';DECLARE vendor_cursor CURSOR FORSELECT BusinessEntityID as VendorID,NameFROM Purchasing.VendorWHERE PreferredVendorStatus = 1ORDER BY BusinessEntityID;
OPEN vendor_cursorFETCH NEXT FROM vendor_cursorINTO @vendor_id, @vendor_name
WHILE @@FETCH_STATUS = 0BEGIN
PRINT ' 'SELECT @message = '---Products
From Vendor: ' + @vendor_namePRINT @message
-- Declare an inner cursor based -- on vendor_id from the outer cursor.DECLARE product_cursor CURSOR FORSELECT p.NameFROM Purchasing.ProductVendor pv,
Production.Product pWHERE pv.ProductID = p.ProductID ANDpv.BusinessEntityID = @vendor_id-- Variable value from the outer cursorOPEN product_cursorFETCH NEXT FROM product_cursor INTO @product
IF @@FETCH_STATUS <> 0 PRINT ' <<None>>'
WHILE @@FETCH_STATUS = 0BEGIN
SET @message = ' ' + @productPRINT @messageFETCH NEXT FROM product_cursor INTO @product
END
CLOSE product_cursorDEALLOCATE product_cursor
-- Get the next vendor.FETCH NEXT FROM vendor_cursorINTO @vendor_id, @vendor_name
ENDCLOSE vendor_cursor;DEALLOCATE vendor_cursor;
Built-in Functions (SQL Server / MySQL)
(Date, String, Math Functions)
CASE Expression and SQL Operators
Built-in (Date) Functions
Function Description
NOW() Returns the current date and time
CURDATE() / CURTIME() Returns the current date/time
DATE() Extracts the date part of a date or date/time expression
EXTRACT() Returns a single part of a date/time
DATE_ADD()/DATE_SUB() Adds/Subtracts a specified time interval to/from a date
DATEDIFF() Returns the number of days between two dates
DATE_FORMAT() Displays date/time data in different formats
Function Description
GETDATE() Returns the current date and time
DATEPART() Returns a single part of a date/time
DATEADD() Adds/Subtracts a specified time interval to/from a date
DATEDIFF() Returns the number of days between two dates
CONVERT() Displays date/time data in different formats
MySQL
SQL Server
http://msdn.microsoft.com/en-us/library/ms174318.aspx
CONVERT(data_type(length),expression,style)Function Description
data_type (length) Specifies the target data type (with an optional length)
expression Specifies the value to be converted
style Specifies the output format for the date/time
Value (YY) Value (YYYY) Input/Output Standard
- 0 or 100 mon dd yyyy hh:miAM (or PM) Default
1 101 mm/dd/yy (mm/dd/yyyy) USA
2 102 yy.mm.dd ANSI
3 103 dd/mm/yy British/French
… … … …
8 108 hh:mm:ss
10 110 mm-dd-yy USA
12 112 Yyyymmdd ISO
- 121 yyyy-mm-dd hh:mi:ss.mmm (24h)
select CONVERT(VARCHAR(10),GETDATE(),110)
Date Data Types
Data Type Format
DATE YYYY-MM-DD
DATETIME YYYY-MM-DD HH:MI:SS
TIMESTAMP YYYY-MM-DD HH:MI:SS
YEAR YYYY or YY
MySQL
SQL Server Data Type Format
DATE YYYY-MM-DD
DATETIME YYYY-MM-DD HH:MI:SS
SMALLDATETIME YYYY-MM-DD HH:MI:SS
TIMESTAMP A unique number
Date Functionsselect CONVERT(VARCHAR(10),GETDATE())select CONVERT(VARCHAR(10),GETDATE(),110)select CONVERT(VARCHAR(24),GETDATE(),112)select CONVERT(VARCHAR(24),GETDATE(),113)select CONVERT(VARCHAR(24),GETDATE(),121)
--year yy, yyyy --- quarter qq, q --- month mm, m --- dayofyear dy, y--day dd, d --- week wk, ww --- weekday dw, w --- hour hh --- minute mi, n--second ss, s --- millisecond ms --- microsecond mcs --- nanosecond ns
--DATEPART(datepart,date)select DATEPART(yy, GETDATE()) --yearselect DATEPART(mm, GETDATE()) --monthselect DATEPART(ww, GETDATE()) --weekselect DATEPART(dw, GETDATE()) --weekdayselect DATEPART(hh, GETDATE()) --hour
--DATEADD(datepart,number,date)select DATEADD(mm, 4, GETDATE())SELECT GETDATE() OrderDate, DATEADD(day,45,GETDATE()) AS OrderPayDate
--DATEDIFF(datepart,startdate,enddate)SELECT DATEDIFF(day,'2008-08-05','2008-06-05') AS DiffDateSELECT DATEDIFF(day,'2008-06-05','2008-08-05') AS DiffDateSELECT DATEDIFF(mm,'2008-06-05','2008-08-05') AS DiffMonthSELECT DATEDIFF(mm,'2008-06-21','2008-08-05') AS DiffMonthSELECT DATEDIFF(yy,'2008-06-21','2008-08-05') AS DiffYear
SELECT DATEDIFF(d,'2001-09-11',GETDATE()) AS DaysPassed, DATEDIFF(mm,'2001-09-11',GETDATE())AS MonthsPassed, DATEDIFF(yy,'2001-09-11',GETDATE()) AS YearsPassed
Built-in (String) FunctionsFunction Description
LEN(str)/LENGTH(str) Returns the length of the string str, measured in bytes
CONCAT(str1, str2, …) Returns the string that results from concatenating the arguments
LOWER(str)/ LCASE(str)UPPER(str) / UCASE(str)
Returns the string str with all characters changed to lowercase/uppercase according to the current character set mapping
LEFT(str,len) / RIGHT(str,len) Returns the leftmost/rightmost len characters from the string str, or NULL if any argument is NULL
SUBSTRING(str, start, len) SUBSTRING(str,pos)/SUBSTRING(str,pos,len)
The forms without a len argument return a substring from string strstarting at position pos. The forms with a len argument return a substring len characters long from string str, starting at position pos
CHARINDEX (exprToFind,exprToSearch, [start_location])LOCATE(substr,str,[pos])
Searches an expression for another expression and returns its starting position if found. If not found returns 0. ([arg] denotes optional argument)
REPLACE(str, from_str, to_str) REPLACE(str, pattern, replacement)
Returns the string str with all occurrences of the string from_strreplaced by the string to_str. Performs a case-sensitive match.(string_pattern is the substring to be found. string_replacementis the replacement string)
LTRIM(str)/RTRIM(str)/TRIM(str) Returns the string str with leading/trailing space characters removed
REVERSE(str) Returns the string str with the order of the characters reversed.
MySQL
SQL Server
String FunctionsSELECT CONCAT('Ahmet ', 'Onur ', 'Durahim')SELECT LOWER('QUADRATICALLY')SELECT UPPER('Maria Gomez')SELECT LEFT(CONCAT('Ahmet ', 'Onur ', 'Durahim'), 4)SELECT RIGHT(CONCAT('Ahmet ', 'Onur ', 'Durahim'), 5)SELECT LEN('Ahmet Onur Durahim')
SELECT SUBSTRING('Quadratically', 0, 5)SELECT CHARINDEX('Onur', 'Ahmet Onur Durahim')SELECT CHARINDEX('to', 'give it to me to him to her')SELECT SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim') + 1, 16)SELECT SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim'), 16)SELECT SUBSTRING('Ahmet Onur Durahim', 0, CHARINDEX(' ', 'Ahmet Onur Durahim'))
SELECT SUBSTRING(SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim') + 1, 16),CHARINDEX(' ', SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim') + 1, 16)) + 1, 10)
SELECT SUBSTRING(SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim'), 16),CHARINDEX(' ', SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim'), 16)), 10)--Use TrimmingSELECT SUBSTRING(LTRIM(SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim'), 16)),CHARINDEX(' ', LTRIM(SUBSTRING('Ahmet Onur Durahim', CHARINDEX(' ', 'Ahmet Onur Durahim'), 16))), 10)--SELECT LTRIM(' barbar ');SELECT RTRIM(LTRIM(' barbar '));----SELECT REPLACE('www.mysql.com', 'w', 'Ww')SELECT REPLACE('sqlserver', 's', 'S')----SELECT REVERSE('www.mysql.com')SELECT REVERSE('Ahmet Onur Durahim')
Built-in (Mathematical) Functions
Function Description
RAND([seed]) Returns a pseudo-random float value from 0 through 1, exclusive
POWER(float_exp, y)POW(float_exp, y)
Returns the value of the specified expression to the specified power
SQRT(float_exp) Returns the square root of the specified float value
ABS(numc_exp) A mathematical function that returns the absolute (positive) value of the specified numeric expression.
CEILING(numc_exp)CEIL(numc_exp)
Returns the smallest integer greater than, or equal to, the specified numeric expression
FLOOR(numc_exp) Returns the largest integer less than or equal to the specified numeric expression
ROUND(numc_exp, length, [function])ROUND(X, [D])
Returns a numeric value, rounded to the specified length or precision. When function is omitted or has a value of 0 (default), num_exp is rounded. When a value other than 0 is specified, num_exp is truncatedD: decimal places
... ...
MySQL SQL Server
http://dev.mysql.com/doc/refman/5.0/en/mathematical-functions.html
Mathematical FunctionsSELECT RAND(100), RAND(), RAND()
SELECT POWER(2, 3) AS Result1, POWER(2.5, 3) AS Result2;
SELECTPOWER(CAST(2.0 AS float), -100.0) AS FloatResult,POWER(2, -100.0) AS IntegerResult,POWER(CAST(2.0 AS int), -100.0) AS IntegerResult,POWER(2.0, -100.0) AS Decimal1Result,POWER(2.00, -100.0) AS Decimal2Result,POWER(CAST(2.0 AS decimal(5,2)), -100.0) AS Decimal2Result;
SELECT SQRT(100)
SELECT ABS(-1.0), ABS(0.0), ABS(1.0);
SELECT CEILING($123.45), CEILING($-123.45), CEILING($0.0);SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45);
SELECT ROUND(748.58, -1), ROUND(748.58, -2)--SELECT ROUND(748.58, -3) --Arithmetic overflow error converting expression to data type numericSELECT ROUND(123.9994, 3), ROUND(123.9995, 3);
SELECT ROUND(150.75, 0);SELECT ROUND(150.75, 0, 1);SELECT ROUND(150.7563, 2, 1); --trancationSELECT ROUND(150.7563, 2); --round
Useful Operators• CASE
SELECT CASE ("column_name")WHEN "value1" THEN "result1"WHEN "value2" THEN "result2"...
[ELSE "resultN"]END
FROM "table_name";
• CAST– CAST ( expression AS data_type [ ( length ) ] )
• CAST & BETWEEN ANDSELECT orderNumber, requiredDateFROM ordersWHERE requiredDate BETWEEN CAST('2003-01-01' AS DATETIME)
AND CAST('2003-01-31' AS DATETIME);
http://msdn.microsoft.com/en-us/library/ms187928.aspx
http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html
CASE Expression--Using a SELECT statement with a simple CASE expressionUSE AdventureWorks2012;GOSELECT ProductNumber, Category =
CASE ProductLineWHEN 'R' THEN 'Road'WHEN 'M' THEN 'Mountain'WHEN 'T' THEN 'Touring'WHEN 'S' THEN 'Other sale items'ELSE 'Not for sale'
END,Name
FROM Production.ProductORDER BY ProductNumber;GO
CASE Expression
USE AdventureWorks2012;
GO
DECLARE @AvgWeight decimal(8,2), @BikeCount int
IF (SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
BEGIN
SET @BikeCount =
(SELECT COUNT(*)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%');
SET @AvgWeight =
(SELECT AVG(Weight)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%');
PRINT 'There are ' + CAST(@BikeCount AS varchar(3)) + ' Touring-3000 bikes.'
PRINT 'The average weight of the top 5 Touring-3000 bikes is ' + CAST(@AvgWeight ASvarchar(8)) + '.';
END
ELSE
BEGIN
SET @AvgWeight =
(SELECT AVG(Weight)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%' );
PRINT 'Average weight of the Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.' ;
END ;
GO
Operators in SQL