70-761 Exam: Querying Data With Transact-SQL (SQL Server: Chapter 3)

  1. Define (a) View, (b) Stored Procedure, and (c) User Defined Function
    • (a) a reusable, named query or table expression that can't contain transactions, error handling, nor parameters
    • (b) routines that support modifying data, underlying structures, error handling, transactions, input/output parameters, temporary tables, and more
    • (c) UDF is a routine that accepts parameters, applies calculations and returns either a scalar or table-valued result.
  2. Write a view schema for a 2016 SP1 database object.
    • USE TSQL4
    • GO
    • CREATE OR ALTER VIEW Sales.OrderTotals 
    • WITH SCHEMABINDING
    • AS
    • XXX
    • GO
  3. What does SCHEMABINDING in a view used for?
    Relative ONLY to views, this option prevents structural changes to dependent tables and columns while the view exists. It's not required by default, but sometime required (ie, when a view is used with an Index). Using it makes things more complex, such as when dealing with upgrades. Such changes as this requires dropping and recreating schema-bound objects before and after the change.
  4. What are the 4 rules for views?
    • (1) No parameters
    • (2) all columns must have names
    • (3) all column names must be unique
    • (4) not allowed to have an ORDER BY clause unless used with TOP or OFFSET-FETCH filter (in either case, order not guaranteed)
  5. Provide a query to get the definition of the existing view called 'OrderTotals'. What happened if I ran the query and received a NULL value?
    SELECT OBJECT_DEFINITION(OBJECT_ID(N'OrderTotals'));

    It means the optional ENCRYPTION keyword was used when creating the view.
  6. Since a view isn't compiled and runs exactly as would the underlying query, what benefits are there to writing one? Any disadvantages?
    Benefits include easy name to remember and query, security via permissions, hides underlying tables, provides computed columns. It has minimal disadvantages of being slower than a stored procedure and if a table is updated, so too will the view need to be.
  7. (a) Can I write an insert or update statement in a view? (b) What is the 'check option' used for? (c) Write a simple 'check option' view.
    (a) No you can't...however, you can outside of the view try to update or insert a value. (b) Similar to a check constraint, it validates that the view update doesn't contradict the view query, that is, it must pass the filter criteria otherwise the update is not allowed

    • (c) CREATE OR ALTER VIEW
    • Sales.USACustomers
    •  custid, companyname, address, city, state
    • FROM Sales.Customes
    • WHERE country = N'USA'
    • WITH CHECK OPTION;
    • GO
  8. Write a statement to create a clustered index on a view and a non-clustered index on that same view.
    • CREATE UNIQUE CLUSTERED INDEX [idx_cl_empid] ON [dbo].[vw_Test]([empid]);
    • CREATE NONCLUSTERED INDEX [idx_nc_orderdate] ON [dbo].[vw_Test]([orderdate]);
  9. What rules are there regarding indexes on views?
    • (a) Only one clustered index but numerous nonclustered
    • (b) view must contain SCHEMABINDING option
    • (c) if query contains grouping, then (1) you must add the BIG_COUNT(*) AS numberoflines element to the select query and (2) the query can't contain any manipulation statements such as CAST / CONVERT.
  10. What are the rules governing user-defined functions?
    • (a) no error handling
    • (b) no modifying underlying data
    • (c) can use dynamic SQL, temporary tables, and DDL's
    • (d) when calling, you must always use the schema (ie, dbo.udf_GetStuff(NULL))
    • (d) complex types can be returned including XML, GEOMETRY, CLR types
    • (e) optional and default parameters can be used
  11. Write a scalar user-defined function which returns the square of a number.
    • CREATE OR ALTER FUNCTION dbo.udf_Square(@input AS INT) 
    • RETURNS INT
    • WITH SCHEMABINDING
    • AS BEGIN

    • return @input * @input;
    • END;
    • GO
  12. Explain how a deterministic and nondeterministic UDF are handled? Provide an example. What would happen if you attempted to put these functions within their own function?
    When you invoke a nondeterministic function in a query, SQL executes it once for the entire query.

    SELECT orderid, SYSDATETIME(), RAND(), NEWID();

    This would return unique items for first and last, but the two middle values would be same throughout all records (NEWID() is an exception).

    Finally, if you attempted to put RAND or NEWID in their own function, it would fail; a work-around would be to put these functions in a view and then call the view.
  13. Create a table with 3 columns, one of which is a column date using a persisted, customized EndOfYear UDF. If it failed for being 'non-deterministic', how would we resolve this?
    • DROP TABLE IF EXISTS dbo.T1;
    • GO 
    • CREATE TABLE dbo.T1
    • (
    •      id INT NOT NULL IDENTITY CONSTRAINT pk_t1 PRIMARY KEY,
    •      dt DAE NOT NULL,
    •      dtEndOfYear AS dbo.EndOfYEar(dt) PERSISTED
    • );

    In order to use a UDF in a persisted, computed column or in an index, the function must be deterministic, so to change, in the function creation, we would need to add SCHEMABINDING to the definition and make sure it returns a unique, deterministic value.
  14. What is a CTE? Write a simple one in an inline function.
    A common table expression which is a temporary table result using the WITH statement and lasting only for the duration of the current query.

    • WITH Sales_CTE (SalesPersonID, NumberOfOrders)
    • AS
    • (
    • SELECT SalesPersonID, COUNT(*)
    • FROM Sales.SalesOrderHeader
    • WHERE SalesPersonID IS NOT NULL
    • GROUP BY SalesPersonID
    • )
    • SELECT AVG(NumberOfOrders) AS "Average Sales Per Person"
    • FROM Sales_CTE;
    • GO
  15. Write a simple recursive CTE used to show the hierarchical nature of employees and managers
    • USE AdventureWorks
    • GO
    • WITH Emp_CTE AS (
    • SELECT EmployeeID, ContactID, LoginID, ManagerID, Title, BirthDate
    • FROM HumanResources.Employee
    • WHERE ManagerID IS NULL
    • UNION ALL
    • SELECT e.EmployeeID, e.ContactID, e.LoginID, e.ManagerID, e.Title, e.BirthDate
    • FROM HumanResources.Employee e
    • INNER JOIN Emp_CTE ecte ON ecte.EmployeeID = e.ManagerID
    • )
    • SELECT *
    • FROM Emp_CTE
    • GO
  16. The recursive CTE structure must contain at least one anchor member and one recursive member. Show pseudocode to show a simple cursive CTE example.
    • WITH cte_name ( column_name [,...n] )
    • AS
    • (
    •      cte_query_definition -- Anchor member is defined.
    •      UNION ALL
    •      cte_query_definition -- Recursive member is defined referencing cte_name.
    • )
    • SELECT * FROM cte_name
  17. What's the difference between an inline table-valued function and a multi-statement function? Which is faster? Why?
    Differences is that a multi-statement function must (a) first declare a table expression to be returns, (b) populate the table, (c) use a BEGIN/END statement, (d) simple RETURN 

    The inline table valued function is quicker because it can leverage SQL optimization whereas MTVF cannot.
  18. Explain stored procedure compilation and speed issues.
    During creation and or altering of a stored procedure, syntax/semantics are pre-parsed for proper use. Once completed and saved, it isn't technically compiled...it is compiled only after it's first execution and then it's query plan cached for later use, making them quicker than other query objects.
  19. What benefits are there to stored procedures?
    Faster, compiled, and cached query plans, ability to use error handling, transactions and parameters, improved security by permissions, hiding of complexity, ability to use all CRUD statements, typically less network traffic since SP handles almost all work and simply receives and sends minimal values via resultset and parameters.
  20. Write a stored procedure called GetOrders using XACT_ABORT and NOCOUNT options
    • CREATE OR ALTER PROC dbo.GetOrders
    • (@orderid AS INT = NULL, @empid AS INT)
    • AS
    • SET XACT_ABORT, NOCOUNT ON

    • SELECT * FROM Sales.Orders O
    • WHERE O.orderid = @orderid AND O.empid = @empid;
    • GO
  21. In a stored procedure, what is XACT_ABORT used for? What is NOCOUNT ON used for?
    XACT_ABORT option determines the effect of run-time errors raised by T-SQL when executing this procedure. If OFF (default), some errors cause an open transaction to roll back and the execution of the code to be aborted whereas others leave the transaction open. To get more reliable errors, best practice says to keep this ON at all times so that an error will be properly rolled back and the execution of code aborted. NOCOUNT option suppresses messages indicating the number of rows were affected by data manipulation statements.
  22. Show how to execute a stored procedure called GetOrders with a default value, NULL, and an id value. Show this same call using best practices. Is order important?
    • EXEC dbo.GetOrders 37, DEFAULT, NULL;
    • EXEC dbo.GetOrders @id = 37;
    • Order is important only when not passing values by name.
  23. Which is faster, dynamic query or regular queries? Explain why. Write a dynamic query?
    Depends on their use...both are cached and the execution plan for the query is reused by subsequent executions. That being said, use of parameters on a dynamic query means its use may not be optimized by SQL cuz it may be using an older version of the query plan compared to the new parameters...to resolve this issue, use WITH RECOMPILE directly after parameter list or with OPTION (RECOMPILE) at end of query ...this will take additional CPU work but make the query optimized for the input parameters provided.

    • DECLARE @query AS NVARCHAR(500);
    • SET @query = 'SELECT * FROM Orders WHERE State = 'CA'';
    • EXECUTE(@query);
  24. Dynamic SQL returns the following permissions error: The SELECT permission was denied on the object 'Orders, database 'TSQLV4', schema 'Sales'. Show a simple fix and then the proper way.
    • Directly after the parameter list, add 'WITH EXECUTE AS OWNER' option. Alternatively, you should provide permissions not just to the SP but also to the underlying tables. Such as:
    • GRANT EXEC ON Sales.Orders TO user1;
    • GRANT EXEC ON dbo.GetOrders TO user1;
  25. Write a stored procedure which uses an output parameter called GetSequenceValue and show how to use it.
    • DECLARE @invoiceid AS INT;
    • EXEC dbo.GetSeqValue @seqname = 'seq', @val = @invoiceid OUTPUT;

    • CREATE OR ALTER PROCEDURE dbo.GetSeqValue (@seqname AS VARCHAR(128), @val AS INT OUTPUT)
    • AS
    • SET XACT_ABORT, NOCOUNT ON;
    • UPDATE dbo.MySequences
    • SET @val = @val + 1 
    • WHERE seqname = @seqname;

    • IF @@ROWCOUNT = 0 THROW 51001, 'Sequence not found', 1;
    • GO
  26. Write a cursor procedure to backup all non-system SQL Server databases.
    • DECLARE @name VARCHAR(50) -- database 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 FOR  
    • SELECT name 
    • FROM MASTER.dbo.sysdatabases 
    • WHERE name NOT IN ('master','model','msdb','tempdb');  

    • OPEN db_cursor   
    • FETCH NEXT FROM db_cursor INTO @name;

    • WHILE @@FETCH_STATUS = 0   
    • BEGIN   
    •        SET @fileName = @path + @name + '_' + @fileDate + '.BAK';  
    •        BACKUP DATABASE @name TO DISK = @fileName;  

    •        FETCH NEXT FROM db_cursor INTO @name;   
    • END   

    • CLOSE db_cursor;   
    • DEALLOCATE db_cursor;
  27. What are the acronyms OLTP and OLAP? Describe each and explain when to use one over the other.
    • On-Line Transaction Processing and On-Line Analytical Processing. OLTP is the typical online database used to manage most every business whereas OLAP is different type of database (data warehouse) which exists as
    • layer on top of another database and is optimized and dedicated to analytics. You typically use a database to insert and manage transactions in a single application while a data warehouse is used to PULL data
    • (analytics), often from numerous applications such as reports, external 3rd parties, internal analysis, etc.
  28. What is a transaction? Define the ACID acronym.
    • A transaction is a unit of work with one or more manipulative tasks to data or structure. ACID: A stands for Atomocity (either completes in entirety or not at all), C for consistency (transition from one consistent
    • state to another), I for isolation (transaction is isolated and transparent), and D for Durability (results are persisted, even in case of system failure).
  29. XACT_ABORT ON is made at the beginning of a SP. If an error occurs in the code, what will happen? What would happen if this option was set to OFF?
    When ON, entired transaction is rolled back and processing stops; If OFF, depending on the severity of the error, the transaction MAY BE rolled back and processing MAY stop, but not always.
  30. When rolling back a transaction, what isn't rolled back? What happens if you don't explicitly define a BEGIN/END?
    • Non-DML (Data Manipulation Lanauge) elements such as local variables, modifying table schema, Deleting of tables or objects, and other statements which don't include the INSERT, UPDATE, DELETE, TRUNCATE, or MERGE
    • statements. If no BEGIN/END is provided in a transaction, then EVERY statement is considered a complete transaction as if it had a BEGIN/END followed by an immediate COMMIT TRAN statement.
  31. What does SET IMPLICIT_TRANSACTIONs ON do?
    • It implies that a BEGIN/END occurs around the entire transaction without explicitly saying so. It's a bad idea to leave this ON since it increases likelyhood of transaction staying on for long periods and degrading
    • performance or blocking other users.
  32. Nesting of transactions is simulated (not technically supported) using @@TRANCOUNT against each BEGIN/END pair. Is a new transaction actually begun this way? Explain.
    No. The BEGIN/END statement only increments, from zero, a counter...such that the user can determine where he/she is, but a new transaction technically isn't being created.
  33. (A) Three BEGIN TRAN statements are made, what is my @@TRANCOUNT? (B) A COMMIT TRAN statement is made. What is my @@TRANCOUNT? (C) Is this transaction committed? (D) A ROLLBACK TRAN statement is made. What is my
    @@TRANCOUNT? (E) What would @@TRANCOUNT had been if instead of ROLLBACK TRAN I had done COMMIT TRAN?
    (A) 3 (B) 2 (C) No (D) 0 (E) 1
  34. If I run the statement 'SELECT * FROM Orders;', SQL immediately runs the statement and returns the results. If I had surrounded this statement by BEGIN/END TRANSACTION then what would have happened?
    • A lock on the Orders table would have been issued and not lifted until after the transaction was either committed or rolled back. If neither were explicitly called and the procedure left...and open transaction
    • would remain.
  35. Write a query to commit all transactions in a procedure. Why is this considered bad practice?
    • WHILE @@TRANCOUNT > 0 COMMIT TRAN; This is considered bad practice because an open transaction may exist (say, from an open transaction from another user which was never closed). Similarly, while XACT_ABORT may be
    • ON, the command to ROLLBACK TRAN may be called but not rolled back properly because an open transaction may have already existed.
  36. An attempt to roll back a transaction fails, the transaction remains open, and the remaining code continues execution. How is this possible? How can we correct this?
    • It's possible by having XACT_ABORT set to OFF and attempting to roll back a transaction that isn't the outermost transaction (first one called). Correctable by turning option to ON resulting in all uncommitted
    • transactions to be rolled back and code processing ending.
  37. Show how to name two transactions, one using WITH MARK. Why is the purpose of this option?
    • BEGIN TRAN T1;
    • UPDATE table1 ...;
    • BEGIN TRAN M2 WITH MARK;
    • UPDATE table 2 ...;
    • The WITH MARK option causes the transaction name to be placed in the transaction log and allowing it to be used by name (as opposed to date/time) when restoring the database).
  38. Name the 6 different error functions used in a CATCH block and explain each. What rules are there regarding these?
    ERROR_NUMBER(); ERROR_MESSAGE();ERROR_SEVERITY(): 0-9 informational and passed to client, 11-19 catch-able, and 20+ are so severe connectivity is terminated;ERROR_STATE(): 1-255;ERROR_LINE() line number where error occurred; ERROR_PROCEDURE():name of stored procedure; Rules state that (a) called outside of a CATCH block returns NULL, (b) these only list last error in the chain, (c) only within current stored procedure.
  39. Create a simple PrintErrorInfo stored procedure using all six error functions
    • CREATE OR ALTER PROC dbo.PrintErrorInfo
    • AS
    • PRINT 'Error Number: ' + CAST(ERROR_NUMER() AS VARCHAR(10));
    • PRINT 'Error Message: ' + ERORR_MESSAGE();
    • PRINT 'Error Severity: ' + CAST(ERROR_SEVERITY() AS VARCHAR(10));
    • PRINT 'Error State: ' + CAST(ERROR_STATE() AS VARCHAR(10));
    • PRINT 'Error Line: ' + CAST(ERROR_LINE() AS VARCHAR(10));
    • PRINT 'Error Procedure: ' + COALESCE(ERROR_PROCEDURE(), 'Not within proc');
    • GO
  40. What's the syntax for THROW and RAISERROR? Which can be re-thrown?
    • THROW error_number, message, state;
    • RAISERROR ({error_id | error_message}, severity, state [,argument [ ,...n ] ]) [WITH options];
    • Both can be re-thrown, but THROW will correctly persist accurate value, is newer, easier to use, and is the one suggested to use by Microsoft.
  41. Write a call to THROW and RAISERROR providing all arguments
    • THROW error_number, message, state; -- THROW 501, 'This is an error', 1;
    • RAISERROR error_number, message, severity, state, WITH OPTION; -- RAISERROR('This is an error', 0, 1) WITH NOWAIT;
  42. What will this error do: RAISERROR('This is an error with severity 20.', 20, 1) WITH NOWAIT, LOG;? What rules used with LOG?
    The error will not wait until the buffer is full (occurs when statement is complete), it will log the result, and since it's severity is 20, it will terminate connectivity. With logs and in transactions, make sure to write to the log only AFTER rolling back transaction and BEFORE the THROW command.
  43. Some errors abort the batch and some don't. Some error abort the transaction and some don't. Some errors even terminate the connection. You can achieve better consistency by doing this which makes your code more robust. Give an example.
    • Turning on XACT_ABORT and by using TRY-CATCH constructs within a transaction. For example, with XACT_ABORT off, division by zero still continues processing the transaction whereas if a CAST error occurred, then
    • processing would stop.
  44. Explain what XACT_STATE() is and how to use it. How is a XACT_ABORT ON error handled?
    • A transaction could be in 3 possible states in a TRY-CATCH block error: open and committable[1], open and uncommittable (doomed)[-1], and no open transaction[0]. You can use this function which returns each of
    • these states in a CATCH block. With XACT_ABORT, the XACT_STATE() returns doomed (-1) which is consistent and suggestable behavior.
  45. DECLARE @x AS INT = NULL, @y AS INT = 1921, @z AS INT = 42; What is the resultset of (A) SELECT COALESCE(@x, @y, @z); (B) SELECT ISNULL(@x, @y); ?
    DECLARE @x AS VARCHAR(3) = NULL, @y AS VARCHAR(10) = '1234567890'; What is the resultset of (C) SELECT COALESCE(@x, @y); (D) SELECT ISNULL(@x, @y); ?
    What is the resultset of (E) SELECT COALESCE('1A2B', 1234); (F) SELECT ISNULL('1A2B', 1234); ? (G) Explain E?
    (A) 1921 (B) 1921 (C) 1234567890 (D) 123 (E) msg: conversion error (F) '1A2B' (G) Highest precedence is an INT so conversion attempt to INT
  46. Compare differences between ISNULL and COALESCE using a table and the 5 differences: parameters, standard, data type of result, nullability of result, and possible # of execution
    • ISNULL: 2, not a standard, type of return type OR if two NULLS then INT, if either null then NOT NULL otherwise NULL, execute only once
    • COALESCE: >2, is a standard, highest precedence data type if not NULL otherwise if all are nulls, you get an error, if ALL input null then NOT NULL otherwise NULL, may be executed more than once
  47. What's the value and type of (A) COALESCE(NULL, NULL)? (B) COALESCE(CAST(NULL AS INT), NULL)? (C) ISNULL(NULL, NULL)? (D) ISNULL(CAST(NULL AS INT), 'abcd')?
    (A) msg: conversion error (B) NULL, INT (C) NULL, INT (D) 'abcd', CHAR(4)
  48. Which is faster, a straight query, a view or a stored procedure?
    Each are their own "beast" and have their own benefits (ie, a view can only express a single SELECT statement). However, if we exclude minor fringe cases, then we could reasonably conclude that a single query is likely the slowest while the stored procedure and view are essentially equivalent with a view maybe lightly improving performance. The reason is that both SP and view's are compiled and cached (making them faster than straight queries), and while both can contain cluster and nonclustered indexes, the view benefits from creating the result set immediately and persisted it, saving the overhead of performing this costly operation at execution time.
  49. When querying two columns in tables A and B which both allow NULL values, what method(s) can be used? Why? Is one better than the other? Do SET OPERATORS behave differently?
    • If a single comparison is made such that A.id = B.id then the NULL value logic states these are 'UNKNOWN' and their results discarded; to prevent this, compare then using one of two ways (1) A.id = B.id OR A.id IS
    • NULL AND B.id IS NULL) or method (2) COALESCE(A.id, 'N/A') = COALESCE(B.id, 'N/A'). The later method is slower since optimization can't take advantage of indexing, so always use method #1. Yes, set operators behave
    • differently--they match based not on equalness, but on distinctness, therefore two NULLS equal true and would be returned in the result set.
Author
mateotete
ID
333222
Card Set
70-761 Exam: Querying Data With Transact-SQL (SQL Server: Chapter 3)
Description
70-761 Exam: Querying Data With Transact-SQL (SQL Server: Chapter 3)
Updated