/
notes for functions
341 lines (288 loc) · 8.07 KB
/
notes for functions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/**************temporary tables**********/
--for intermediate storage, mostly
--one type
--limited to one session, private to the session
use Community_Assist
--Local temp table
Create Table #TempGrants --has # in front, this denotes a local, session-specific temp table
(
GrantRequestKey int,
GrantRequestDate datetime,
PersonKey int,
GrantTypeKey int,
GrantRequestAmount money
)
Insert into #TempGrants(GrantRequestKey, GrantRequestDate, PersonKey, GrantTypeKey, GrantRequestAmount)
Select GrantRequestKey, GrantRequestDate, PersonKey, GrantTypeKey, GrantRequestAmount from GrantRequest
Where month(GrantRequestDate)=9
Select * from #TempGrants
--another type is global
Create Table ##TempGrantsGlobal --has ## in front, this denotes a global temp table
(
GrantRequestKey int,
GrantRequestDate datetime,
PersonKey int,
GrantTypeKey int,
GrantRequestAmount money
)
Insert into ##TempGrantsGlobal(GrantRequestKey, GrantRequestDate, PersonKey, GrantTypeKey, GrantRequestAmount)
Select GrantRequestKey, GrantRequestDate, PersonKey, GrantTypeKey, GrantRequestAmount from GrantRequest
Where month(GrantRequestDate)=9
Select * from ##TempGrantsGlobal
--visible to everyone that is logged in
/*************functions**************/
--for calculations that are unique to your db
--scalar function that operates row by row
Go
Create function fx_Cube
(@number int)--separate multiple parameters with comma
returns int
As
Begin
Declare @Cube int
Set @Cube = @number * @number * @number
Return @Cube
End
Go
Select dbo.fx_Cube(3) as [Cube]
Select PersonKey, dbo.fx_Cube(PersonKey) as cubed from Person
Order by cubed
--a function to make a percentage
Go
Alter Function fx_PercentAmount
(@amount money, @percentage decimal(10, 2))--parameters
returns money --return type
As
Begin
if(not @amount=0)--check to make sure not zero
Begin--start outer if
if (@percentage > 1)
Begin
Set @percentage = @percentage / 100
End--end outer if
Declare @result money--declare variable for result
Set @result = @amount * @percentage--calculate amount
End--end outer if
Else--begin else
Begin
Set @result=0;
End--end else
return @result--return results
End
select sum(DonationAmount), dbo.fx_PercentAmount(sum(DonationAmount), 20) as Org,
dbo.fx_Percentamount(sum(DonationAmount), .8) as charity
From Donation
/***********stored procedures*******/
--groups of sql code that execute as a single executable thread
--useful for controlling things like how users update tables, inserts etc
--because of error trapping and isolation
--parameterized view
use Community_Assist
go
create procedure usp_HRViewProc --user stored procedure
@EmployeeKey int
As --as always starts the body
Select PersonLastName,
PersonFirstName,
PersonEmail,
EmployeeHireDate,
EmployeeAnnualSalary
From Person p
inner join Employee e
on p.PersonKey=e.PersonKey
Where EmployeeKey = @EmployeeKey --the only difference between this and a view is that we're passing in a variable ALSO
--in a view you would select against it, can't do that with a stored procedure, you have to execute it
exec usp_HRViewProc 2
go
--create hash password function
Create function fx_hashPasword2
(@seed int, @password nvarchar(50))
returns varbinary(500)
As
Begin
Declare @newPassword nvarchar(70)
Set @newPassword=@password + cast(@seed as nvarchar(20))
Declare @hashed varbinary(500)
set @hashed=hashbytes('sha2_512',@newPassword)
return @hashed
End
--new person stored procedure
go
alter proc usp_NewPerson
@LastName nvarchar(255),
@FirstName nvarchar(255)=null,
@Email nvarchar(255),
@Password nvarchar(50),
@AptNumber nvarchar(255)=null,
@Street nvarchar(255),
@City nvarchar(255)='Seattle',
@State nvarchar(255)='WA',
@Zip nvarchar(255),
@HomePhone nvarchar(255)
As
--test to see if exists
if exists
(Select PersonLastName, PersonEmail from Person
Where PersonLastName=@LastName and Personemail=@Email)
Begin
Print 'Already registered'
Return
End
--create pasword hash
Declare @seed int
Set @seed = dbo.fx_GetSeed()
declare @HashedPass varbinary(500)
set @HashedPass = dbo.fx_HashPassword(@seed, @password)
begin tran --start a transaction
begin try --begin try
--insert into person
Insert into Person(
PersonLastName, PersonFirstName,
PersonEmail, PersonPassWord,
PersonEntryDate, PersonPassWordSeed)
Values (@LastName, @FirstName, @Email, @HashedPass, GetDate(), @seed)
declare @key int = ident_current('Person')--returns most recent insert
Insert into PersonAddress(
PersonAddressApt, PersonAddressStreet,
PersonAddressCity, PersonAddressState,
PersonAddressZip, PersonKey)
Values(@AptNumber, @Street, @City, @State, @Zip, @Key)
Insert into Contact(
ContactNumber, ContactTypeKey, PersonKey)
Values(@HomePhone, 1, @Key)
Commit Tran --commit the transaction if no error
End Try
Begin Catch
Rollback Tran
Print Error_Message()
End Catch
exec usp_NewPerson
@LastName = 'Kong',
@FirstName = 'King',
@Email = 'kingkong@bananas.com',
@Password = 'KongPass',
@Street = '101 Jungle Blvd',
@Zip = '98102',
@HomePhone = '2065558989'
--stored procedure to update address
Create proc usp_UpdateAddress
@PersonAddressApt nvarchar(255) = null,
@PersonAddressStreet nvarchar(255),
@PersonAddressCity nvarchar(255) = 'Seattle',
@PersonAddressState nvarchar(255) = 'WA',
@PersonAddressZip nvarchar(255),
@PersonKey int
As
Begin Tran
Begin Try
Update PersonAddress
Set PersonAddressApt = @PersonAddressApt,
PersonAddressStreet = @PersonAddressStreet,
PersonAddressCity = @PersonAddressCity,
PersonAddressState = @PersonAddressState,
PersonAddressZip = @PersonAddressZip
Where PersonKey = @PersonKey
Commit Tran
End Try
Begin Catch
Rollback Tran
print error_message()
End Catch
Select * from PersonAddress
exec usp_UpdateAddress
@PersonAddressApt = '50000',
@PersonAddressStreet = '100 South Mann Street',
@PersonAddressZip = '98001',
@PersonKey = 1
/***********triggers************/
--stored procedure that is triggered by an event
--usually insert, update, and delete
--can also execute on CREATE or DROP
--have no parameters so you can pass values to them.
--some happen after (for) an event, some happen instead of an event (intercepts and doesn't allow the action to happen)
create trigger Tr_PersonDelete on Person
instead of Delete
As
if not exists
(Select name from sys.Tables
where name = 'PersonDelete')
Begin
CREATE TABLE [dbo].[PersonDelete](
[PersonKey] int NOT NULL,
[PersonLastName] nvarchar(255) NOT NULL,
[PersonFirstName] nvarchar(255) NULL,
[PersonEmail] nvarchar(255) NULL,
[PersonPassWord] varbinary(500) NULL,
[PersonEntryDate] datetime NOT NULL,
[PersonPassWordSeed] int NULL,
)
End
INSERT INTO PersonDelete(
PersonKey,
PersonLastName,
PersonFirstName,
PersonEmail,
PersonPassword,
PersonEntryDate,
PersonPasswordSeed
)
Select PersonKey,
PersonLastName,
PersonFirstName,
PersonEmail,
PersonPassword,
PersonEntryDate,
PersonPasswordSeed
From deleted --temp table in temp db that stores deletions and updates
select * from Person
insert into Person(
PersonLastName,
PersonFirstName,
PersonEmail,
PersonEntryDate)
values('nothere', 'long', 'nothere@long.com', GetDate())
delete from Person where PersonKey = 132
select * from PersonDelete
--check to see f request is larger than maximum allowed
Create Trigger tr_CheckMax on GrantRequest
for Insert
as
if not exists
(select name from sys.tables
Where name ='OverMax')
Begin
Create Table OverMax
(
RequestDate date,
PersonKey int,
GrantTypeKey int,
Explanation nvarchar(255) null,
RequestAmount money,
)
End
Declare @GrantMax money
Declare @GrantType int
Declare @RequestAmount money
Select @GrantType=GrantTypeKey from inserted
Select @GrantMax = GrantTypeMaximum from GrantType
where GrantTypeKey = @GrantType
Select @RequestAmount = GrantRequestAmount from inserted
if @RequestAmount > @GrantMax
Begin
Insert into OverMax(
RequestDate,
PersonKey,
GrantTypeKey,
Explanation,
RequestAmount)
Select GrantRequestDate, PersonKey, GrantTypeKey, GrantRequestExplanation, GrantRequestAmount
from inserted
End
select * from GrantType
insert into GrantRequest(GrantRequestDate,
PersonKey,
GrantTypeKey,
GrantRequestExplanation,
GrantRequestAmount)
values (GetDate(),1,1,'Always hungry', 300.00)
select * from OverMax