SQL Exam 7
SQL Exam 7
The main parts of a loop are the starting point, counter, counter increment and end point
- once you have these the rest of the loop is just the tasty filling:
Set the initial value of the counter to your year of birth, and loop until this reaches the
current year (use year(GetDate())). You can then use the counter within your loop to filter a
select statement counting the number of events.
The hardest part in creating this query is changing the month number into the month
name, as sadly there is no in-built function. Here's one way to achieve this:
Create an integer variable to hold the value whose primeness you're testing
Use WHILE to loop until this integer is 1000, incrementing its value by 1 each
time round the loop (let's call this number P)
Find out the square root of the number you're testing (use SQRT)
Find out what the highest integer is just below this (use FLOOR) - let's call this X
Try dividing each number from 1 up to and including X into P
If we ever find a number such that P % X = 0 (ie that P leaves a remainder of 0
when divided by X) we have a non-prime, and we should flag this accordingly
and break out of the loop
The start of the time test - at the end, set @EndTime and use DateDiff(ms, @StartTime, @EndTime)
to work out the difference in milliseconds
5/1 =5
5/2 = 2 plus a remainder
5/3 = 1 plus a remainder
5/4 = 1 plus a remainder
5/5 =1
5/6 = 0 plus a remainder
... = 0 plus a remainder
4/1 = 4
4/2 = 2
4/3 = 1 plus a remainder
4/4 = 1
4/5 = 0 plus a remainder
... = 0 plus a remainder
You give the function a number and the output is "Yes" if the number is
prime, or "No" if it is not.
Now suppose you want to calculate the first 100 prime numbers. A
flowchart to show that process is shown below.
The flowchart above starts with the number 2 and checks each number
3, 4, 5, and so forth. Each time it finds a prime it prints the number and
increments a counter. When the counter hits 100, it stops the process.
To determine whether a number is prime, it calls the function
"IsThisNumberPrime" which is shown at the top of this page.
The first few primes are quickly calculated, but as the primes get further
apart the computation time increases. Finding large primes is a task for
super computers.
SQL exercises on TRANSACTIONS –(5)
Finally, display a list of all of the doctors (the rows from the tblDoctor table). Now run
your query - it should show the original 12 doctors (Shaun the Sheep has not beeen
added).
Amend your query to test whether 2 + 2 = 5, and rerun it. You should now get your new
doctor:
The transaction has been committed, and the new doctor appears in the list.
Manually delete this added row, then (optionally) save this query as Baad
example.sql and close it down.
Just saying....
Now change the code to add (Holiday destination) to the other countries within a
transaction. After running the update statement:
Change the condition to test whether 1 + 1 = 3 (it doesn't), and rerun it. Check that the
extra text has been added:
If you have nothing better to do, change Holiday to Visited for countries you've been to.
Finally, as a bit of housekeeping please reset the country names by running this query:
If you could also manually reset the name of your home country back to its former glory, that would
be good! Thanking you ...
Optionally save this as Stake your claims.sql, and then close it down.
Now we can turn this insert into a transaction - but first, write a delete command to
remove any events with an Eventname like My DOB.
Note that to do this you will first need to get SQL Server to overwrite the ContinentId identity
column by running the command SET IDENTITY_INSERT tblContinent ON. Don't forget to turn
this property off at the end of your query.
After running the Insert statement, comment it out but leave the variable.
You should now see Westeros appearing in the list of continent names when you select them. The
question is: which is the deadliest continent?
Start a TRANSACTION to delete the continent held in the variable, using this syntax:
DELETE tblContinent
WHERE ContinentName = @Continent
If the first letter of your name is not equal to (<>) the first letter of the variable (W) then
roll back the transaction:
In this case, show the message You have died and update the continent name of Westeros to Seven
Kingdoms, then select all the continents.
Set the ELSE condition to show You have won and to then select all the continents.
The outcome now will depend on your name. If it is W then you will see no continent:
You survived and the seven kingdoms of Westeros are gone. Danny would be proud!
For those less fortunate of us, you will have died. Change the <> to an = and rerun the
script. This time you should see Seven Kingdoms and a happier message.
Write an update query which will set this column to equal the number of enemies for
each episode (but within a transaction), then:
Roll back this transaction if more than 100 rows are affected (displaying a
suitable message, as shown below); or
Commit it otherwise and show a list of all of the episodes, including the newly
populated field.
Use @@RowCount to see how many rows are affected, but don't forget to store this in a variable
immediately after running the update so that its value doesn't get overwritten.
When you run this query, you should see something like this:
Because 117 rows were updated, your query should roll back the transaction.
Now change the threshold in the query from 100 to 120 and re-run it. This time the
query should update the column, and display the results:
You have to wait until episode id 15 to get more than one enemy (at which point 3 come along at
once).
When you've got this working, optionally save your query as Counting your
enemies.sql, then close it down.
Now add a varchar(max) parameter called @TableName to hold the name of the table
from which you want to extract data, and use its value in place of tblEvent in
the FROM clause. Sadly this doesn't work and results in an error:
Declare a varchar(max) variable called @SQL, and set it equal to the SQL script up to
the FROM keyword, then add your parameter value on the end:
Then finally either use EXEC (@SQL) or Exec SP_SQLEXEC @SQL at the bottom of
the stored procedure to run the select statement contained in your variable.
Try passing in each of the tblEvent, tblCountry and tblContinent table names.
Declare and build up a string variable called @sql which contains a SELECT command
based on the value of these two parameters, and execute it like this:
You should now be able to list the Doctor Who episodes in different orders! For
example:
When you've got this working, optionally save the query as Allsorts.sql, then close it
down.
Dynamic SQL
3. If you haven't already done so, run the stored procedure in the above
folder to generate a database of training courses and attendees.
Your stored procedure should build up a string of text containing a SQL command, then
execute it:
You should then be able to run your stored procedure (when you've finished it!) to show
data from different tables in different ways. For example:
Two completely different SELECT statements, using the same stored procedure
If it helps, here's the sort of string of text you should be aim to be building up: SELECT TOP 5
FirstName,LastName FROM tblPerson ORDER BY LastName.
Optionally, save the code to generate your stored procedure as Variable inputs.sql,
then close it down.
Now use this list to filter another select statement which shows all of (*) the information
about those events from the event table. You will need to use dynamic SQL:
The top 5 results for the same owl.