You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Practice/SQLPreclass - session 14.sql
+327Lines changed: 327 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -0,0 +1,327 @@
1
+
/*Stored Procedure Basics
2
+
A stored procedure in SQL Server is a group of one or more Transact-SQL statements or a reference to a Microsoft .NET Framework common runtime language (CLR) method. Procedures resemble constructs in other programming languages because they can:
3
+
4
+
Accept input parameters and return multiple values in the form of output parameters to the calling program.
5
+
Contain programming statements that perform operations in the database. These include calling other procedures.
6
+
Return a status value to a calling program to indicate success or failure (and the reason for failure).
7
+
Benefits of Using Stored Procedures
8
+
Reduced server/client network traffic
9
+
Stronger security
10
+
Reuse of code
11
+
Easier maintenance
12
+
Improved performance*/
13
+
14
+
CREATEPROCEDURE sp_FirstProc AS
15
+
BEGIN
16
+
SELECT'Welcome to precedural world.'ASmessage
17
+
END
18
+
19
+
EXECUTE sp_FirstProc
20
+
/* Otherwise, using the ALTER PROCEDURE as below, you can change the query you wrote in the procedure.*/
21
+
GO
22
+
ALTERPROCEDURE sp_FirstProc AS
23
+
BEGIN
24
+
PRINT'Welcome to procedural world.'
25
+
END
26
+
27
+
EXECUTE sp_FirstProc
28
+
29
+
/*When you want to remove the stored procedure, you can use:*/
30
+
31
+
DROPPROCEDURE sp_FirstProc
32
+
33
+
/* Stored Procedure Parameters
34
+
In this section, we demonstrate how to use input and output parameters to pass values to and from a stored procedure.
35
+
36
+
Parameters are used to exchange data between stored procedures and functions and the application or tool that called the stored procedure or function:
37
+
38
+
Input parameters allow the caller to pass a data value to the stored procedure or function.
39
+
Output parameters allow the stored procedure to pass a data value or a cursor variable back to the caller.
40
+
Every stored procedure returns an integer return code to the caller. If the stored procedure does not explicitly set a value for the return code, the return code is 0. */
41
+
42
+
-- Create a procedure that takes one input parameter and returns one output parameter and a return code.
/* You can assign a default value for the parameters. If any value that is used as a parameter value is NULL, then the procedure continues with the default parameter.
When a variable is first declared, its value is set to NULL. To assign a value to a variable, use the SET statement.
106
+
107
+
This is the preferred method of assigning a value to a variable. A variable can also have a value assigned by being referenced in the select list of a SELECT statement.
108
+
109
+
To assign a variable a value by using the SET statement, include the variable name and the value to assign to the variable. This is the preferred method of assigning a value to a variable.*/
110
+
111
+
--Declare a variable
112
+
DECLARE @Var1 VARCHAR(5)
113
+
DECLARE @Var2 VARCHAR(20)
114
+
115
+
--Set a value to the variable with 'SET'
116
+
SET @Var1 ='MSc'
117
+
118
+
--Set a value to the variable with 'SELECT'
119
+
120
+
SELECT @Var2 ='Computer Science'
121
+
122
+
--Get a result by using variable value
123
+
124
+
SELECT*
125
+
FROM departments
126
+
WHERE graduation = @Var1
127
+
AND dept_name = @Var2
128
+
129
+
-- Declare a variable
130
+
DECLARE @Var1 VARCHAR(5)
131
+
132
+
-- Set a value to the variable with 'SET'
133
+
SET @Var1 ='MSc'
134
+
135
+
-- Use the variable in a query
136
+
SELECT*FROM departments WHERE graduation = @Var1;
137
+
138
+
--Declare a variable
139
+
DECLARE @Var1 bigint
140
+
141
+
--Set a value to the variable with "SELECT"
142
+
SELECT @Var1 = id
143
+
FROM departments
144
+
145
+
--Call the variable
146
+
SELECT @var1 AS last_id;
147
+
/*IF Statements
148
+
IF statements in SQL allow you to check if a condition has been met and, if so, to perform a sequence of actions. This secture teaches you everything from the basic syntax of IF statements, including how to use the ELSE clause and perform multiple actions using a BEGIN and END block.
149
+
150
+
The SQL statement that follows an IF keyword and its condition is executed if the condition is satisfied: the Boolean expression returns TRUE. The optional ELSE keyword introduces another SQL statement that is executed when the IF condition is not satisfied: the Boolean expression returns FALSE.*/
151
+
152
+
IFDATENAME(weekday, GETDATE()) IN (N'Saturday', N'Sunday')
153
+
SELECT'Weekend'AS day_of_week;
154
+
ELSE
155
+
SELECT'Weekday'AS day_of_week;
156
+
157
+
/* In the query above, If statement checks if today is saturday or sunday. If today is saturday or sunday, Query returns "Weekend", If not returns "Weekday". */
158
+
159
+
IF1=1PRINT'Boolean_expression is true.'
160
+
ELSEPRINT'Boolean_expression is false.' ;
161
+
162
+
/* In the query above, If statement checks "1 = 1" equality. If the equality is confirmed, Query returns the first message, If not returns the second message. */
163
+
164
+
/* WHILE Loops
165
+
In SQL Server there is only one type of loop: a WHILE loop. This secture teaches you how to use them, from the basic syntax of the WHILE statement, through how to use a SELECT statement within a loop.
166
+
167
+
The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.*/
168
+
169
+
SELECTCAST(4599.999999ASnumeric(5,1)) AS col
170
+
171
+
/*In the following query, we'll generate a while loop. We'll give a limit for the while loop, and we want to break the loop when the variable divisible by 3. In this example we use WHILE, IF, BREAK and CONTINUE statements together.*/
172
+
173
+
-- Declaring a @count variable to delimited the while loop.
174
+
DECLARE @count asint
175
+
176
+
--Setting a starting value to the @count variable
177
+
SET @count=1
178
+
179
+
--Generating the while loop
180
+
181
+
WHILE @count <30-- while loop condition
182
+
BEGIN
183
+
SELECT @count, @count + (@count *0.20) -- Result that is returned end of the statement.
184
+
SET @count +=1-- the variable value raised one by one to continue the loop.
185
+
IF @count % 3=0-- this is the condition to break the loop.
186
+
BREAK-- If the condition is met, the loop will stop.
187
+
ELSE
188
+
CONTINUE-- If the condition isn't met, the loop will continue.
189
+
END;
190
+
191
+
/* User Defined Functions
192
+
Like functions in programming languages, SQL Server user-defined functions are routines that accept parameters, perform an action, such as a complex calculation, and return the result of that action as a value. The return value can either be a single scalar value or a result set.
193
+
194
+
*/
195
+
196
+
/* In the following batch, created an user-defined scalar-valued function dbo.ufnGetAvgSalary(). The function gets an input parameter: @seniority. Then, calculated the average salary according to the value/object assigned to @seniority parameter. The variable @avg_salary, declared in the function, catches the result average salary. Finally, the function returns @avg_salary variable as a result. */
SELECTdbo.ufnGetAvgSalary('Candidate') as avg_salary
214
+
215
+
SELECT
216
+
*
217
+
FROM
218
+
departments
219
+
220
+
/* Table-Valued Function Example:
221
+
222
+
In the following batch, created an user-defined table-valued function dbo.dept_of_employee(). The function gets an input parameter: @dept_name. In the RETURNS statement we specify the return type of the function. Finally, in the RETURN statement we specify what will return the function among the parentheses.
Like functions in programming languages, SQL Server user-defined functions are routines that accept parameters, perform an action, such as a complex calculation, and return the result of that action as a value. The return value can either be a single scalar value or a result set.
249
+
250
+
251
+
252
+
💡Why use user-defined functions (UDFs)?
253
+
254
+
They allow modular programming.
255
+
You can create the function once, store it in the database, and call it any number of times in your program. User-defined functions can be modified independently of the program source code.
256
+
They allow faster execution.
257
+
Similar to stored procedures, user-defined functions reduce the compilation cost of the code by caching the plans and reusing them for repeated executions.
258
+
They can reduce network traffic.
259
+
An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then be invoked in the WHERE clause to reduce the number of rows sent to the client.
260
+
261
+
Types of Functions
262
+
Scalar-valued Functions
263
+
Scalar-valued functions return a single data value of the type defined in the RETURNS clause. For an inline scalar function, the returned scalar value is the result of a single statement. For a multistatement scalar function, the function body can contain a series of Transact-SQL statements that return the single value.
264
+
265
+
Table-Valued Functions
266
+
User-defined table-valued functions return a table data type. For an inline table-valued function, there is no function body; the table is the result set of a single SELECT statement.
267
+
Scalar-Valued Function Example:
268
+
269
+
"departments" table:
270
+
271
+
In the following batch, created an user-defined scalar-valued function dbo.ufnGetAvgSalary(). The function gets an input parameter: @seniority. Then, calculated the average salary according to the value/object assigned to @seniority parameter. The variable @avg_salary, declared in the function, catches the result average salary. Finally, the function returns @avg_salary variable as a result.
272
+
273
+
CREATE FUNCTION dbo.ufnGetAvgSalary(@seniority VARCHAR(15))
274
+
RETURNS BIGINT
275
+
276
+
277
+
call the function:
278
+
279
+
SELECT dbo.ufnGetAvgSalary('Senior') as avg_salary
280
+
281
+
282
+
result:
283
+
284
+
285
+
Table-Valued Function Example:
286
+
287
+
In the following batch, created an user-defined table-valued function dbo.dept_of_employee(). The function gets an input parameter: @dept_name. In the RETURNS statement we specify the return type of the function. Finally, in the RETURN statement we specify what will return the function among the parentheses.
288
+
289
+
CREATE FUNCTION dbo.dept_of_employee (@dept_name VARCHAR(15))
290
+
RETURNS TABLE
291
+
292
+
293
+
call the function:
294
+
295
+
SELECT * FROM dbo.dept_of_employee('Music')
296
+
297
+
298
+
result:
299
+
300
+
Here is another example of table-valued function:
301
+
302
+
Table-valued function dbo.raised_salary() gets an input parameter @name. In the RETURNS statement we generate a table variable @raised_salary. Then, as the main process, insert the values we want to get as a result. A RETURN statement with a return value cannot be used in this context. Finally, writing the RETURN statement we mention that what will return the function among the parentheses.*/
GOCREATEFUNCTIONdbo.dept_avg_salary(@graduation char(3))RETURNSTABLEASRETURN ( SELECT dept_name, AVG(salary) avg_salary FROM departments WHERE graduation = @graduation GROUP BY dept_name);GOSELECT*FROM dept_avg_salary('PhD')GOCREATEFUNCTIONdbo.dept_avg_salary2(@dept_name VARCHAR(20), @graduation char(3))RETURNSTABLEASRETURN ( SELECT dept_name = @dept_name, AVG(salary) avg_salary FROM departments WHERE graduation = @graduation AND dept_name = @dept_name --GROUP BY dept_name);GOSELECT * FROM dept_avg_salary2('Computer Science', 'MSc')SELECT dept_name, AVG(salary) OVER(PARTITION BY dept_name)FROM [dbo].departmentsWHERE graduation = 'MSc' AND dept_name ='Computer Science'--GROUP BY dept_nameGOCREATE FUNCTION dbo.raised_salary4 (@name varchar(20)) RETURNS TABLE AS RETURN ( SELECT id, name, salary + (salary * 0.20) raised_salary FROM departments WHERE name = @name) ;GOSELECT * FROM raised_salary4('Eric')
0 commit comments