Skip to content

Commit 4666189

Browse files
authored
Add files via upload
1 parent 2a181cc commit 4666189

File tree

1 file changed

+327
-0
lines changed

1 file changed

+327
-0
lines changed

Practice/SQLPreclass - session 14.sql

Lines changed: 327 additions & 0 deletions
Original file line numberDiff line numberDiff 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+
CREATE PROCEDURE sp_FirstProc AS
15+
BEGIN
16+
SELECT 'Welcome to precedural world.' AS message
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+
ALTER PROCEDURE 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+
DROP PROCEDURE 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.
43+
44+
CREATE PROCEDURE sp_SecondProc @name varchar(20), @salary INT OUTPUT
45+
AS
46+
BEGIN
47+
48+
-- Set a value in the output parameter by using input parameter.
49+
SELECT @salary = salary
50+
FROM departments
51+
WHERE name = @name
52+
53+
-- Returns salary of @name
54+
RETURN @salary
55+
END
56+
GO
57+
-------------------call/execute the procedure:
58+
-- Declare the variables for the output salary.
59+
DECLARE @salary_output INT
60+
61+
-- Execute the stored procedure and specify which variable are to receive the output parameter.
62+
EXEC sp_SecondProc @name = 'Eric', @salary = @salary_output OUTPUT
63+
64+
-- Show the values returned.
65+
PRINT CAST(@salary_output AS VARCHAR(10)) + '$'
66+
GO
67+
68+
--run all of these together
69+
70+
SELECT
71+
*
72+
FROM
73+
departments
74+
75+
/* 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.
76+
77+
Let's modify the procedure "sp_SecondProc": */
78+
79+
ALTER PROCEDURE sp_SecondProc @name varchar(20) = 'Jack', @salary INT OUTPUT
80+
AS
81+
BEGIN
82+
83+
-- Set a value in the output parameter by using input parameter.
84+
SELECT @salary = salary
85+
FROM departments
86+
WHERE name = @name
87+
88+
-- Returns salary of @name
89+
RETURN @salary
90+
END
91+
GO
92+
93+
/*Declaring a Variable
94+
The DECLARE statement initializes a variable by:
95+
96+
Assigning a name. The name must have a single @ as the first character.
97+
Assigning a system-supplied or user-defined data type and a length. For numeric variables, precision and scale are also assigned.
98+
Setting the value to NULL.*/
99+
100+
DECLARE @myfirstvar INT
101+
102+
DECLARE @LastName NVARCHAR(20), @FirstName NVARCHAR(20), @State NCHAR(2);
103+
104+
/*Setting a value in a variable
105+
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+
IF DATENAME(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+
IF 1 = 1 PRINT 'Boolean_expression is true.'
160+
ELSE PRINT '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+
SELECT CAST(4599.999999 AS numeric(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 as int
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. */
197+
198+
CREATE FUNCTION dbo.ufnGetAvgSalary(@seniority VARCHAR(15))
199+
RETURNS BIGINT
200+
AS
201+
-- Returns the stock level for the product.
202+
BEGIN
203+
DECLARE @avg_salary BIGINT
204+
205+
SELECT @avg_salary = AVG(salary)
206+
FROM departments
207+
WHERE seniority = @seniority
208+
209+
RETURN @avg_salary
210+
END;
211+
212+
SELECT dbo.ufnGetAvgSalary('Senior') as avg_salary
213+
SELECT dbo.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.
223+
224+
*/
225+
226+
CREATE FUNCTION dbo.dept_of_employee (@dept_name VARCHAR(15))
227+
RETURNS TABLE
228+
AS
229+
RETURN
230+
(
231+
SELECT id, name, salary
232+
FROM departments
233+
WHERE dept_name=@dept_name
234+
);
235+
236+
SELECT * FROM dbo.dept_of_employee('Music')
237+
238+
/* Relational DB & SQL_C15_EU_US
239+
Dashboard
240+
My courses
241+
RDB&SQL_C15
242+
SQL Programming Basics
243+
SQL Programming with T-SQL
244+
245+
SQL Programming with T-SQL
246+
To do: Go through the activity to the end
247+
User Defined Functions
248+
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.*/
303+
304+
CREATE FUNCTION dbo.raised_salary (@name varchar(20))
305+
RETURNS @raised_salary TABLE
306+
(
307+
id BIGINT,
308+
name NVARCHAR(20),
309+
raised_salary BIGINT
310+
)
311+
AS
312+
BEGIN
313+
INSERT @raised_salary
314+
SELECT id, name, salary + (salary * 0.20)
315+
FROM departments
316+
WHERE name = @name
317+
RETURN
318+
END
319+
320+
SELECT * FROM dbo.raised_salary('Eric')
321+
322+
SELECT
323+
*
324+
FROM
325+
departments
326+
327+
GOCREATE FUNCTION dbo.dept_avg_salary(@graduation char(3))RETURNS TABLEASRETURN ( SELECT dept_name, AVG(salary) avg_salary FROM departments WHERE graduation = @graduation GROUP BY dept_name);GOSELECT * FROM dept_avg_salary('PhD')GOCREATE FUNCTION dbo.dept_avg_salary2(@dept_name VARCHAR(20), @graduation char(3))RETURNS TABLEASRETURN ( 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

Comments
 (0)